ReferenceError: Cannot access store before initialization

Viewed 2445

I have this store/index.ts

export const storeRedux = createStore(
  persistReducer(ReduxPersistConfig, rootReducer),
  composeEnhancers(applyMiddleware(sagaMiddleware))
);

And have this implementation to access the token outside of component

//api.ts

import axios from 'axios';
import { storeRedux } from 'store';

let token;

const listener = () => {
  token = storeRedux.getState().user.token;
};

storeRedux.subscribe(listener);

// console.log(() => getAPI());

export default axios.create({
  baseURL: 'http://localhost:5000/api/security',
  headers: {
    Authorization: `Bearer ${token}`,
  },
 
});

If I'll add a setTimeout to wrap the getState() then everything will be alright.

Is there any other solution since store is already separated just like in this article

0 Answers
Related