Answer the question
In order to leave comments, you need to log in
How to properly implement localStorage in Redux?
Good afternoon.
I decided to add local storage to my Redux program (comments), put the code in a separate folder:
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);
} catch (err) {}
};
import React from "react";
import ReactDOM from "react-dom";
import App from "./containers/app";
import { createStore } from "redux";
import comments from "./reducers";
import { loadState, saveState } from "./localStorage/localStorage";
import "./styles.css";
const persistedState = loadState();
const store = createStore(comments, persistedState);
store.subscribe(() => {
saveState(store.getState());
});
ReactDOM.render(<App store={store} />, document.querySelector("#app"));
const initialState = [];
const store = createStore(comments, initialState);
Answer the question
In order to leave comments, you need to log in
I suppose the problem is that on the first load you create a state with the value undefined. If you have undefined in persistedState when you open the page, then in the editor it is impossible for the state to be undefined. It can be an empty array (as in the case of initialState), an empty object, an empty string, but not undefined. For good, you need to check what lies inside persistedState when opening the page, and dance further from this. Sorry for being so vague, I don't have access to a laptop and you didn't attach a screenshot of the error, so I'm shooting for luck.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question