1

I have a React-Redux store which is wrapped in a next-redux-wrapper. I want to dispatch a function outside of react component but I am unable to do so because of the wrapper. Is there a way to import store and use dispatch while using wrapper?

export const rootReducer = combineReducers({
    [authSlice.name]: authSlice.reducer
});
const sagaMiddleware = createSagaMiddleware();

const makeConfiguredStore = () => {
   const store = configureStore({
   reducer: rootReducer,
   middleware: [sagaMiddleware],
   devTools: true,
 });
 sagaMiddleware.run(rootSaga);
 return store;
};

export const makeStore = () => {
  const persistConfig = {
    key: 'nextjs',
    whitelist: ['auth'],
    storage,
  };

  const persistedReducer = persistReducer(persistConfig, rootReducer);

  const store: any = configureStore({
    reducer: persistedReducer,
    middleware: [sagaMiddleware],
    devTools: process.env.NODE_ENV !== 'production',
  });

  sagaMiddleware.run(rootSaga);
  store.__persistor = persistStore(store); // Nasty hack
  return store;
}

export const wrapper = createWrapper<AppStore>(makeStore);

export type AppStore = ReturnType<typeof makeStore>;
export type AppState = ReturnType<AppStore['getState']>;

I am trying to use this on a axios helper file, For example:


const setHeaders = async () => {

  const token = await refreshOrAccessToken();

  if(!token){
    // const store = makeStore();

    store.dispatch(signoutUser(SESSION_EXPIRY_MSG))
    msalInstance.logoutRedirect();
    throw Error(SESSION_EXPIRY_MSG)
  }
  axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
};
3
  • You may be able to create a store object first, then create a function that returns it instead of creating a store. Can you edit to include an example minimal reproducible example where you are wanting/trying to access the store outside the expected areas? Commented Jan 10, 2024 at 17:21
  • Hi @DrewReese, I have edited the code snipped including a place where I need to access the store. Commented Jan 11, 2024 at 7:43
  • From the above snippet, I am able to dispatch signoutUser function but, its just for the name sake, Its not doing any activities at all, not updating data to local storage or doing anything at all. Whereas if I call the same from a react component, It is updating the persist store data Commented Jan 11, 2024 at 9:55

1 Answer 1

0

I believe you should be able to create the store normally and rework the makeStore function to simply return the store.

Example:

export const rootReducer = combineReducers({ ...multiple_reducers_here });
const sagaMiddleware = createSagaMiddleware();

const persistConfig = {
  key: 'nextjs',
  whitelist: ['auth'],
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store: any = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware => getDefaulrMiddleware().concat(sagaMiddleware),
  devTools: process.env.NODE_ENV !== 'production',
});
export const persistor = persistStore(store);

sagaMiddleware.run(rootSaga);

export const makeStore = () => store;

export const wrapper = createWrapper<AppStore>(makeStore);

export type AppStore = ReturnType<typeof makeStore>;
export type AppState = ReturnType<store.getState>;

You should now be able to import the exported store in your code and call store.dispatch to dispatch actions to the same store instance that is provided to your app code.

Sign up to request clarification or add additional context in comments.

2 Comments

Using this, I am getting following error: Uncaught TypeError: Cannot read properties of undefined (reading 'subscribe')
@AnkitShah Can you edit the post to share that complete error message and accompanying stacktrace? Can you also clarify if this is occurring server-side or client-side?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.