SOLVED
We found a literally two minutes after posting this question... Our solution was this:
let state:any;
store.subscribe(() => {
state = store.getState();
});
I'm building a React app with Redux and redux-persist. I have a problem with accessing Redux state outside a React component. If I subscribe to the store and console log the state it shows the correct state with data inside it, but when I console log the state outside (const state = store.getState();
) the subscribe arrow function (store.subscribe(() => console.log(store.getState()))
) the data inside the store is empty. And when I use the useSelector hook, inside a React component, it works fine. This is a really weird bug since it appeared two weeks after I wrote the code using the store outside a React component. Has anyone had a similar bug?
This is my Redux config.
// Redux.
import { createStore, applyMiddleware, compose } from "redux";
// Redux-thunk.
import thunk from "redux-thunk";
// Reducers.
import reducers from "../reducers";
// Storage.
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, reducers);
const composeEnhancers =
(window["__REDUX_DEVTOOLS_EXTENSION_COMPOSE__"] as typeof compose) ||
compose;
const middleWare = applyMiddleware(thunk);
const store = createStore(persistedReducer, composeEnhancers(middleWare));
const persistor = persistStore(store)
export {store, persistor};
state
as a variable outside the subscribe callback should not affect behavior, becausegetState()
always returns a reference to whatever the current state value is. Can you add more details on what you're actually trying to do, how, and why?getState
.