Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: Cannot access store before initialization

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

like image 239
ajbee Avatar asked Jul 03 '26 22:07

ajbee


1 Answers

I know it's old, but question w/o answer sores my eye.

You have to assure the order of execution of the dependent code, you need to register listener once store is initiated. You can do this for example with the init method:

// api.ts
import { AnyAction, Store, Unsubscribe } from "redux";
import axios from 'axios';

let token;

export const initApi = (store:Store<TState, AnyAction>):Unsubscribe => {
  return store.subscribe(()=>{
    token = store.getState().user.token;
  })
}


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

Note The TState describes your state e.g.

export type TState = {
  // ...
  user: { token: string; }
}

now, you can use it after store is initiated

// store/index.ts
import { initApi } from '../location/to/api.ts'; 

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


initApi(storeRedux);

export { storeRedux };


like image 195
Lukasz 'Severiaan' Grela Avatar answered Jul 06 '26 12:07

Lukasz 'Severiaan' Grela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!