0

I'm trying automatically add to all axios requests an access token and I'm using (or trying to) a middleware. But I'm getting the following error: 'store' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

store/index.ts

import { configureStore } from '@reduxjs/toolkit';
import { routerMiddleware } from 'connected-react-router/immutable';
import { createBrowserHistory } from 'history';
import { setIsAxiosAuthorized } from './middlewares';
import createRootReducer from './reducers';

export const history = createBrowserHistory();

export const store = configureStore({
  reducer: createRootReducer(history),
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(
      routerMiddleware(history),
      setIsAxiosAuthorized
    ),
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;

export type AppDispatch = typeof store.dispatch;

middlewares.ts

import { authManager } from 'src/features/auth/authManager';
import { authActions } from 'src/features/auth/redux';
import { RootState } from '.';

export const setIsAxiosAuthorized = (store: RootState) => (next) => (
  action
) => {
  authManager.setAxiosAuthorizationToken();
  store.dispatch(authActions.setIsAxiosAuthorized(true));
  return next(action);
};

Is my middleware incorrect? How can I make it typed (I've tried different approaches from StackOverflow, but they are causing different errors)?

juliano.net
  • 7,982
  • 13
  • 70
  • 164
  • RootState is not a store, right? It's a rootState. But you are calling it as if it has a dispatch function. Perhaps the circular type inference here would work if there wasn't an error in it. – cefn May 15 '21 at 13:03
  • Did you mean to have a third introspected type `export type Store = typeof store` and use that? – cefn May 15 '21 at 13:06
  • However, after you have fixed this, I have also seen very similar examples where the circularity was too complex for the typescript compiler to do inference, but there was nothing actually wrong with the code. In my case I have had to explicitly define the State type as its own state and annotate the type of the Store explicitly in order to limit the circularity. – cefn May 15 '21 at 13:09

0 Answers0