I'm trying to make a to-do app.
First, I detect the change in the input and assign it to the state named todo.
const [todo, setTodo] = useState("");
const handleChange = (e) => {
setTodo(e.target.value);
}
then i try to add the information in todo to the todos state, which is empty array when the button is clicked.
const [todos, setTodos] = useState([]);
const handleClick = () => {
setTodos(todos.push(todo));
console.log(todos);
}[enter image description here][1]
At the first click, it adds as seen below. However, on the second click I get the following error: Uncaught TypeError: todos.push is not a function
The full code is as follows:
const [todo, setTodo] = useState("");
const [todos, setTodos] = useState([]);
const handleChange = (e) => {
setTodo(e.target.value);
}
const handleClick = () => {
setTodos(todos.push(todo));
console.log(todos);
}
return(
<>
<input type="text" onChange={handleChange} />
<button onClick={handleClick}>add</button>
</>
)
}
I'm wondering where i went wrong.
CodePudding user response:
Use the spread operator.
Also you state mutation won't update in time for the console log below to be fired, use a useEffect()
and pass todos
as the dependancy for it to watch for updates on and pass the console log into there.
const [todo, setTodo] = useState("");
const [todos, setTodos] = useState([]);
const handleChange = (e) => {
setTodo(e.target.value);
}
const handleClick = () => {
setTodos([...todos, todo]);
// This will spread in the previous todos, then place todo within the array.
setTodo('');
// also, looking at your code, you probably need to empty todo afterwards.
}
useEffect(() => {
console.log(todos);
}, [todos])
return(
<>
<input type="text" onChange={handleChange} />
<button onClick={handleClick}>add</button>
</>
)