Answer the question
In order to leave comments, you need to log in
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
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);
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question