DEV Community

Junior Oliveira
Junior Oliveira

Posted on • Originally published at dev.to on

Persisting application state with Redux and localStorage

Note: It was originally wrote in Portuguese and translated by Google

This library allows you to monitor the status of the application (Redux store) and replicate in localStorage (browser), thus allowing the page to be reloaded without the state being lost.

  • The first step is to import the library and inform the store
import { createStore, combineReducers } from 'redux'
import storeSynchronize from 'redux-localstore'
import { Reducer1, Reducer2 } from './modules'

const combineReducer = combineReducers({  
 Reducer1,  
 Reducer2  
})

export const store = createStore(combineReducer)

storeSynchronize(store)
Enter fullscreen mode Exit fullscreen mode

Only with bold lines, the entire state of your application will be replicated to the browser ‘s localStorage. The other rows are default settings for Redux application.

  • As second step, you need to configure the reducers so that they collect this data from the localStorage when the application starts / reloads.
import { defineState } from 'redux-localstore'

const defaultState = {
  data: null
}

const initialState = defineState(defaultState)('Reducer1')

export default (state = initialState, action) => {
  switch (action.type) {
    case 'ACTION1':
      return {
        ...state,
        data: action.payload
      }
    case 'ACTION2':
      return {
        ...state,
        data: null
      }
    default:
      return state
  }
}
Enter fullscreen mode Exit fullscreen mode

The method defineState checks if it has something in localStorage , if it does, it uses it as the initial state … Otherwise, it uses the default state set. Very simple, is not it?

The only detail to note is that the name passed as the second argument to the defineState is the name of the Reducer used in the combineReducers .

The settings are basically these and you can find the library at: https://github.com/arojunior/redux-localstore

Top comments (0)