Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outside of the handleSubmit function, it works fine. Any insights on why this setup isn't functioning as expected would be greatly appreciated. Thank you!
import { useState } from 'react';
import Header from './components/Header';
import List from './components/List';
import React from 'react';
import uniqid from 'uniqid';
function App() {
const [todoList, setTodoList] = useState([]);
const [todo, setTodo] = useState({
name: '',
complete: false,
id: ''
});
const [error, setError] = useState(false);
function handleChange(e) {
setTodo({
...todo,
name: e.target.value,
});
}
function handleAdd(newTodo) {
setTodoList([
...todoList,
newTodo
])
}
function handleSubmit(e) {
e.preventDefault();
if (!todo.name) {
setError(true);
} else {
handleAdd({
...todo,
id: uniqid()
})
setError(false);
setTodo({
...todo,
name: ''
})
console.log(todo);
}
}
function handleDelete(id) {
const todoListItems = todoList.filter(todo => todo.id !== id);
setTodoList(todoListItems);
}
function handleClear() {
setTodoList([]);
}