How to trigger action on mount, but after redux storage load

642 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

I added a new state field reduxStorageLoaded, initially false, and added a case to my reducer:

import { LOAD } from 'redux-storage';

...

const mainReducer = (state = initialState(), action) => {
  switch (action.type) {
    ...
    case LOAD:
      return {
        ...state,
        reduxStorageLoaded: true,
      };
    ...

and wrapped my whole app in a conditional based on this new state variable reduxStorageLoaded so it only mounted once it becomes true, which is when redux-storage has fully loaded and dispatched the LOAD action.