I use redux-storage
for persisting the redux state tree across refreshes, etc.
redux-storage-engine-localstorage
as the storage engine.
My problem has to do with the order of
1) the action which loads this persisted state, and
2) some other action I set off in a componentDidMount
lifecycle function.
Because the storage load happens after some action I trigger, the action I trigger might as well not have happened, since the old state overwrites it.
Printing out the action type at the top of my reducer, on page load I see:
action.type @@redux/INIT
action.type HIDE_MODAL
action.type REDUX_STORAGE_LOAD
action.type REDUX_STORAGE_SAVE
action.type FETCH_USER_FAILURE
action.type REDUX_STORAGE_SAVE
The HIDE_MODAL
action is triggered in one of my components' componentDidMount
method.
The storage load happens before mounting my root node (right after creating my redux store):
import mainReducer from './reducers';
const reducer = storage.reducer(mainReducer);
const storageEngine = createEngine(some key);
const storageMiddleware = storage.createMiddleware(storageEngine);
const middleware = applyMiddleware(
storageMiddleware,
);
const storageLoad = storage.createLoader(storageEngine);
const store = createStore(
reducer,
middleware,
);
storageLoad(store);
render(
<Provider store={store}>
...
</Provider>,
document.getElementById('root')
);
Why does the REDUX_STORAGE_LOAD
not happen before everything else, and is there a way to make sure it occurs before everything else?
I added a new state field
reduxStorageLoaded
, initiallyfalse
, and added a case to my reducer:and wrapped my whole app in a conditional based on this new state variable
reduxStorageLoaded
so it only mounted once it becomestrue
, which is whenredux-storage
has fully loaded and dispatched theLOAD
action.