S
S
Sergey2019-12-26 18:20:15
JavaScript
Sergey, 2019-12-26 18:20:15

How to solve LocalStorage issue in an application via Redux?

Good afternoon, I decided to finalize the comments section written through Redux and add saving to localStorage. However, when trying to add a comment, the console issues Cannot read property 'push' of null. I can't figure out what the problem is.
Below is the reducer code.

const comments = (state = [], action) => {
  switch (action.type) {
    case "ADD_COMMENT":
      let componentDidMount = localStorage.getItem("comms");
      componentDidMount = JSON.parse(componentDidMount);
      const addCommentObj = {
        id: action.id,
        name: action.name,
        date: action.date,
        comment: action.comment
      };

      componentDidMount.push(addCommentObj);
      let toLocalStor = JSON.stringify(componentDidMount);
      localStorage.setItem("comms", toLocalStor);
      return [
        ...state,
        {
          id: action.id,
          name: action.name,
          date: action.date,
          comment: action.comment
        }
      ];

    case "REMOVE_COMMENT":
      return state.filter(el => el.id !== action.payload.id);

    default:
      return state;
  }
};

export default comments;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Suntsev, 2019-12-26
@GreyCrew

Very strange code. But the problem is on the surface. You don't have data in localStorage initially, and you are trying to call the push method in null, although it is available only for arrays.
do so
instead of

let componentDidMount = localStorage.getItem("comms");
componentDidMount = JSON.parse(componentDidMount);

A
abberati, 2019-12-26
@abberati

When the item is not in localStorage, the getItem method returns null. You can't push to null - it's not an array.
Not related to the question, but: you can't do side effects in reducers. Read the doc.

R
Robur, 2019-12-26
@Robur

componentDidMount is null.
try
but in general json.parse should be wrapped in try / catch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question