S
S
Sergey2020-01-02 23:58:25
JavaScript
Sergey, 2020-01-02 23:58:25

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) {}
};

As a result, the original index file looks like this:
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"));

However, in order to "push" the persistedState constant into the store, I had to remove the initialState (before the changes, the code looked like this and worked fine
const initialState = [];

const store = createStore(comments, initialState);

)
After removing the initialState and compiling via webpack, the application does not open and gives an error (although in codesandbox, where I originally wrote the code, everything works). That is, as far as I understand, after compilation, the problem is precisely in the absence of initialState.
Tell me, please, how can I competently implement this - and leave initialState and put localStorage?
By the way, the guide from which I took this implementation was written by Den Abramov himself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladyslav Kliuiev, 2020-01-03
@TrueBlackBox

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 question

Ask a Question

731 491 924 answers to any question