简体   繁体   中英

How to keep redux state when page refreshed

Following Dan Abramov method for storing state in localStorage I am unable to retain the existing state of my app after carrying out a page refresh. Using redux dev tools, when I log in, state is authenticated and user is stored. When the page is refreshed the log just clears and goes back to "@@INIT"

My code for index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import rootReducer from './reducers/rootReducer';
import { loadState, saveState } from './localStorage';
import { BrowserRouter } from 'react-router-dom';
import { composeWithDevTools } from 'redux-devtools-extension';

const middleware = [thunk];
const composeEnhancers = composeWithDevTools({
  thunk
});

const persistedState = loadState();
const store = createStore(
  rootReducer,
  persistedState,
  composeEnhancers(applyMiddleware(...middleware))
);

store.subscribe(() => {
  // saves states to localStorage everytime state changes
  saveState(store.getState());
});

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);
registerServiceWorker();

code for localStorage.js

export const loadState = () => {
  try {
    const serializedState = localStorage.getItem('state');
    if (serializedState === null) {
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    return undefined;
  }
};

export const saveState = state => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem('state', serializedState);
    console.log('this is the state', state);
  } catch (err) {
    // Ignore errors
  }
};

// Ignore errors

Don't Ignore the errors, at least log them to see if the state is being set in localstorage or giving some error.

Also Can you confirm that the state is being saved in the localStorage at the first place?

Realised I was using the redux dev tools incorrectly. Following Dan Abramov tutorial helps but a good recommendation is to log the errors which is where I realised I was working correctly. My fault was that I was using the redux inspector, not log monitor!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM