0

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};

3
  • Your problem description seems a bit odd. Where and how are you needing to access the Redux store outside of React? And the listed solution seems very wrong. Declaring state as a variable outside the subscribe callback should not affect behavior, because getState() 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? Jan 29, 2020 at 15:24
  • We need to access state outsite React to compare a websockets message with the current state in redux to see if we need to dispatch the message, because otherwise it will dispatch to Redux every second. Jan 31, 2020 at 23:13
  • Consider handling the websocket in a middleware instead. That's the general recommended place for using websockets in Redux, and it also has access to getState. Feb 3, 2020 at 0:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.