Search code examples
javascriptreduxlocal-storagelit-element

Saving redux store to localstorage - with lit-element


Currently I'm trying to store a subset of my redux-state to localstorage. I was using the documentation from PWA Starter Kit to implement a basic storage, which works fine for now, but this only saves the complete state to the localstorage.

This isn't exactly what I want, because as mentioned, I only want to store a subset, like some specific action results (e.g. state.settings instead of state).

Every documentation and examples only store the complete state, I haven't found any comment that fits my need.

My current implementation

redux-store.js

import {
  createStore,
  applyMiddleware,
  compose as origCompose,
  combineReducers
} from 'redux';
import thunk from 'redux-thunk';
import { lazyReducerEnhancer } from 'pwa-helpers/lazy-reducer-enhancer';
import { loadState, saveState } from './redux-localstorage';

import applicationReducer from './reducers/application-reducer';

export const store = createStore(
  (state, action) => state,
  loadState(),
  compose(lazyReducerEnhancer(combineReducers), applyMiddleware(thunk))
);

export default store;

store.addReducers({
  applicationReducer
});

store.subscribe(() => {
  saveState(store.getState());
});

redux-localstorage.js

const STORAGE = '__RDX_STORAGE_TEST__';

export const saveState = state => {
  const json = localStorage.getItem(STORAGE) || '{}';
  const stringifiedNewState = JSON.stringify(state);

  if (stringifiedNewState !== json && stringifiedNewState !== '{}') {
    localStorage.setItem(STORAGE, stringifiedNewState);
  }
};

export const loadState = () => {
  const json = localStorage.getItem(STORAGE) || '{}';
  const state = JSON.parse(json);
  return state || undefined;
};

So, my question is: is this even possible? If yes, how can I achive this?

Thanks a lot.


Solution

  • Using the basic PWA Starter Kit as a base, if for example you wanted to store the shop state and the counter state but not the app state, you could do something like this:

    const STORAGE = '__RDX_STORAGE_TEST__';
    
    export const saveState = state => {
      const json = localStorage.getItem(STORAGE) || '{}';
      // take only the parts we need
      const {shop, counter} = state;
      const stringifiedNewState = JSON.stringify({shop, counter});
    
      if (stringifiedNewState !== json && stringifiedNewState !== '{}') {
        localStorage.setItem(STORAGE, stringifiedNewState);
      }
    };
    
    export const loadState = () => {
      const json = localStorage.getItem(STORAGE) || '{}';
      const state = JSON.parse(json);
      return state || undefined;
    };

    This way only those two sections will be written to localStorage