简体   繁体   中英

Using localstorage setItem/getItem with react-redux

I'm new to redux and I can't seem to find an answer that that works with my problem. When I try to insert the localstorage as shown in this solution -> Where to write to localStorage in a Redux app? ...

I get an error saying my state is undefined later in the thread, and I'm not sure why.

Here is the full app in sandbox -> https://codesandbox.io/s/5yn3kqqlkk (I recommend using with chrome)

If I try to uncomment the lines in the following file...

import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";
import "./Style.css";
import App from "./App";
import reducer from "./reducers";

let persistedState = localStorage.getItem("reduxState")
  ? JSON.parse(localStorage.getItem("reduxState"))
  : {};

const store = createStore(
  reducer,
  // persistedState,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

// store.subscribe(() => {
//   localStorage.setItem('reduxState', JSON.stringify(store.getState()));
// });

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

The app crashes with the property in the state being read as undefined -> https://i.imgur.com/h0kcpBD.png

Can anyone tell me why this is happening and what I'm doing wrong?

Looks like the issue was with the persistentState else condition was setting an empty object instead of undefined (which was what the error message was reading). So it was mutating the state as an empty object instead of leaving it alone.

solution code...

let persistedState = localStorage.getItem("reduxState")
  ? JSON.parse(localStorage.getItem("reduxState"))
  : undefined;

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