DEV Community


Discussion on: Recursive Loop in Redux Reducer to check integrity of local Storage

markerikson profile image
Mark Erikson

As a simplified example, you could have a higher-order reducer that looks for a "PERSISTED_DATA_LOADED" action and returns that:

function loadPersistedData(wrappedReducer) {
    return function persistedDataReducer(state, action) {
        if(action.type === "PERSISTED_DATA_LOADED") {

        return wrappedReducer(state, action);

You could also have each individual slice reducer look for "PERSISTED_DATA_LOADED" and separately respond by pulling the bit of data it cares about out of or action.payload or whatever you want to call it, and return that.

As for setup, typically persistence handling is done when you're creating the store on app startup, either by grabbing the persisted data first and passing it to createStore(), or dispatching some kind of "load the data" action right after you create it:

const preloadedState = JSON.parse(localStorage.get("persistedReduxState"));
const store = createStore(rootReducer, preloadedState);

// or
const store = createStore(rootReducer);

const preloadedState = JSON.parse(localStorage.get("persistedReduxState"));

if(preloadedState) {
     store.dispatch({type : "PERSISTED_STATE_LOADED", data : preloadedState});

But, as I said in my first reply, there's many existing libs that do this kind of stuff for you automatically once you set them up.

Thread Thread
nodefiend profile image
chowderhead Author

whoa! this is genius!

thank you so much for taking time to explain this to me !

its much clearer seeing the code for it.

Didnt even cross my mind to have a higher order reducer , what a great idea !

Will suggest a change to our team !

But first, I will look into the other library options for this first of course!

thanks again so much for your time