DEV Community

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

Collapse
 
nodefiend profile image
chowderhead

Wow!

thank you so much for the suggestions, we are actually in the process of refactoring our actions and stores to a new version, and i can fit your suggestions into the new version of the reducer

  • we will definitely be taking it out of component did mount.
  • using an external library to handle local storage sounds like a good idea, especially if its a library tailored to redux.
  • thanks for your suggestion about removing local storage from the reducer , i wouldnt of known another way.
  • my senior engineer actually suggested that this be built this way, so i will bring up these suggestions when we refactor

  • i dont quite understand what you mean by loading the data as its own distinct action?

  • it is its own action , that happens once at the root component . could you maybe show me a code example of what you mean?!

thanks so much for reading ! :D really appreciate your time

Collapse
 
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 action.data;
        }

        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 action.data 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

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