How to persist Redux State to the Local Storage

FrontEnd Reading Time: 3 min.

  • views3273
  • 1comment
Share

Redux is a great library which solves many issues related to keeping a state of an application. Thanks to it, we no longer have to worry about the hierarchy of components. The central store can be accessed from every component to get the current state of any aspect of an application. Working with code is also clearer since action codes are placed in one location.
Perfect as it may sound, there is no possibility of retrieving data from a previous save in case of its loss. Fortunately, there are many other libraries which are perfectly capable of it. One of the most popular is redux-persist.

What is Redux Persist?

Redux-persist is a simple library; it’s a wrapper for a store that automatically saves a redux state to the storage. We can define where it should save data, and available options depend on a platform; we can choose localStorage, sessionStorage, localForage, AsyncStorage or we can even integrate it with the custom storage. They just have to be able to respond to standard methods like setItem, getItem, removeItem and getAllKeys.

Configuration

As with any other library, before we start using Redux Persist we have to add it to the current project. The simplest way is by using npm command:

$npm install --save redux-persist --save

If a library has them already installed, we have to reconfigure our default redux store. Settings for the storage code might look like the one below:


import { persistStore } from 'redux-persist'

const enhancer = compose(
    applyMiddleware(thunk, promise),
    devTools({
           name: 'NativeStarterKit', realtime: true
    }),
);

let store = createStore(reducer, enhancer);
persistStore(store, {storage: AsyncStorage}, onCompletion);

return store

In the above code we are using the import function to load persistStore method from redux-persist library. Next, we call this method with a newly created Redux store as a first argument. As a second argument, we define which storage we would like to (in our case, is an AsyncStorage). And finally, the last argument is a callback function which will be fired when rehydration finishes.
This wrapper is not only responsible for saving the state but also for force calling REHYDRATE action on all reducers. Thanks to it we are able to restore the last saved state to reducers when an application is initialized. To do this, we have to rework our reduced additionally by adding a new handler for REHYDRATE action.


..

import { REHYDRATE } from 'redux-persist/constants'

..

if (action.type === REHYDRATE){

    // retrive stored data for reducer callApi
    const savedData = action.payload.callApi || InitialState;     
    
    return {
        ...state, ...savedData
    };
}

This is it! A few modified lines of a code allow us to enjoy a persisting state of our application.

Tagged with:

Tags:

  • Hasyim

    Hi! Very useful piece of information. I understand that a new handler for REHYDRATE action has to be defined in the reducer, but what I dont get is how/when will this action be triggered? Will this be triggerred automatically when i start up the application? And from my (limited) understanding of AsyncStorage, i thought it is a key-value pair. So how does redux-persis know which key to retireve from the local storage?