I’m trying to add localStorage to my Todo on React, but I getting an error Cannot read properties of null (reading ‘concat’) when I try to add new todo item. How to fix it? Here my code:
import { useState, useEffect } from 'react';
import TodoInput from './TodoInput';
import TodoList from './TodoList';
import './App.css';
const App = () => {
const [todo, setTodo] = useState('');
const [todos, setTodos] = useState([]);
const localStorage = window.localStorage;
const [localTodos, setLocalTodos] = useState([]);
useEffect(() => {
setLocalTodos(JSON.parse(localStorage.getItem('todos')));
}, []);
function addTodo() {
if (todo !== '') {
setLocalTodos(JSON.parse(localStorage.getItem('todos')));
localTodos = localTodos.concat([todo]);
localStorage.setItem('todos', JSON.stringify(localTodos));
setTodo('');
}
};
function deleteTodo(text) {
localTodos = JSON.parse(localStorage.getItem('todos'));
localTodos = localTodos.filter((todo) => {
return todo !== text;
});
setLocalTodos(localTodos);
};
return (
<div className="App">
<h1>Your todos</h1>
<TodoInput todo={todo} setTodo={setTodo} addTodo={addTodo} />
<TodoList list={localTodos} remove={deleteTodo} />
</div>
);
}
export default App;
2
Answers
You have to create a copy of the state so you can update this latter and then use it
You have to make those changes in both your
deleteTodo
andaddTodo
functionsAlso you can initilize your state with the value from localstorage
There’s a lot more to the problem than just that one error:
Also, consider this approach logically. You just queued an update to that state value on the immediate previous line. If you want to update state to a concatenated value, first concatenate the value and then update state.
For example:
Don’t forget to also update the call to
setItem
to use thenewTodos
value, sincelocalTodos
won’t have been updated yet at that time.