re: Add Offline-Caching to Your React Reducer with 5 Lines of Code VIEW POST

TOP OF THREAD FULL DISCUSSION
re: What happens when more than one reducer stores data under the my-state key? What happens when one wants to upgrade the structure of of the store be...
 

What happens when more than one reducer stores data under the my-state key?

Very weird stuff ! It's not at all recommended to do that.

What happens when one wants to upgrade the structure of of the store between deployments?

It's recommended to change the state key when changing the structure of the store (e.g. my-state-1, my-state-2)

What happens when the store contains a Map or an instantiated class or a function?

This technique as is, requires the state to be serializable, to handle special cases you would need to add custom parsing and stringifying for non-serializable variables or simply ignore them when reading and writing to the the cache.

 

Cool, why not cover those cases and write a hook to manage them?

const useCachedReducer = (
  reducer,
  initialState,
  storeKey,
  serializer = JSON.stringify,
  deserializer = JSON.parse
) => {
  // Likely these should be memoized
  const init = deserializer(localStorage.getItem(storeKey)) || initialState;
  const cachedReducer = (state, action) => {
    const newState = reducer(state, action);
    localStorage.setItem(storeKey, serializer(newState));
    return newState;
  }
  return React.useReducer(cachedReducer, init);
}

Thanks for taking the time to write that !

The main reason I didn't go into it, is to keep the code under 5 lines 😅

I wanted the reader to quickly understand the idea of using HOFs with the reducer and build on it and experiment themselves.

Now they can also read/use this hook 👌

code of conduct - report abuse