Whenever I try to put something into my to-do list, there is always an empty element at the first index. Why does this happen?
const [todoList, setTodoList] = useState([]); const addToList = (inputText) => { if (inputText === "") { alert("The list is empty") }else{ setTodoList([inputText, ...todoList]) } console.log(todoList); }; const addList = (inputText) => { addToList(inputText); };
const [todoList, setTodoList] = useState([]); const addToList = (inputText) => { if (inputText === "") { alert("The list is empty") }else{ setTodoList([...todoList, inputText]) } console.log(todoList); }; const addList = (inputText) => { addToList(inputText); };
I also tried it but it didn’t work
Your
Use a closure to get the
todoList
, so you get the sametodoList
every time.You need to do something like this: