redux-persist: How to save state on browser's local storage?

Viewed 5485

I am learning redux and wanted to know how can I save the state locally so when I refresh after making some changes to state it remains. I came to know about redux-persist and saw the github doc describing how to use it but its not very clear to me.

Here is the index.js code of my app -

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('#container'));

How can I achieve it ?

2 Answers
//In your createStore have this code    
import { applyMiddleware, compose, createStore } from 'redux'
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import rootReducer from '../reducers';
import { persistReducer } from 'redux-persist'
import localForage from 'localforage';
const loggerMiddleware = createLogger();

export default (initialState = {}) => {
  // ======================================================
  // Middleware Configuration
  // ======================================================
  const middleware = [thunkMiddleware, loggerMiddleware]

  // ======================================================
  // Store Enhancers
  // ======================================================



  const enhancers = []
  const __DEV__ = process.env.NODE_ENV !== 'production';
  if (__DEV__) {
    const devToolsExtension = window.devToolsExtension
    if (typeof devToolsExtension === 'function') {
      enhancers.push(devToolsExtension())
    }
  }

  // ======================================================
  // Store Instantiation and HMR Setup
  // ======================================================
  let config = {
    key: 'root',
    storage: localForage,
    whitelist: ['user'],
    debug: __DEV__
  }
  let configureReducer = persistReducer(config, rootReducer)
  const store = createStore(
    configureReducer,
    initialState,
    compose(
      applyMiddleware(...middleware),
      ...enhancers
    ),
  )

  return store
}


// In your App.js or root app, do this in your componentDidMount

persistStore(
      store,
      undefined,
      () => {
        console.log('callback::')
      }
    )

Here is what you should do for creating your store, using redux-persist in store.js:

    import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
    import { persistStore, autoRehydrate } from 'redux-persist';
    import localForage from 'localforage';
    import { routerReducer } from 'react-router-redux';

    import reducers from './container/reducers';
    import middlewares from './middlewares';

    const reducer = combineReducers({
    ...reducers,
    routing: routerReducer,
    });

    export const initStore = (state) => {
    const store = createStore(
        reducer,
        {},
        compose(
        applyMiddleware(...middlewares),
        autoRehydrate(),
        ),
    );

    persistStore(store, {
        storage: localForage,
        whitelist: ['login'],
    });

    return store;
    };

In your app.js, create your store this way:

import React from 'react';

import { Provider } from 'react-redux';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';

import createRoutes from './routes'; // Contains the routes
import { initStore, persistReduxStore } from './store';
import { appExample } from './container/reducers';

const store = initStore(appExample);

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { rehydrated: false };
  }

  componentWillMount() {
    persistReduxStore(store)(() => this.setState({ rehydrated: true }));
  }

  render() {
    const history = syncHistoryWithStore(browserHistory, store);
    return (
      <Provider store={store}>
        {createRoutes(history)}
      </Provider>
    );
  }
}
Related