I'm learning react at the moment and currently, making a todo app so that I can understand react more easily. So here's what I'm trying to do:
- The user clicks a button
- The click fires a prompt which asks the user for the todo title (only title at the moment)
- Then, that title is added to an array of all todos
- And then, use that array to display each todo on the page
Code:
const [check, setCheck] = useState(false);
const [todo, setTodo] = useState([]);
function handleClick() {
let toAdd = prompt('Title: ')
setTodo([...todo, {
title: toAdd
}]);
}
useEffect(()=> {
if(todo.length !== 0) {
setCheck(true);
}
})
return (
<div className="wholeContainer">
<div className="tododiv">
<span className="todos">Todos: </span>
<hr/>
{
check ?
todo.forEach((eachTodo)=> {
<TodoItems title={eachTodo}/>
})
: <span>Nothing</span>
}
</div>
<button className="add" onClick={handleClick}>
<i className="fas fa-plus"></i>
Add a Todo
</button>
</div>
);
The const [check, setCheck] = useState(false);
is written so that I can access the array if todo.length !== 0
;
The problem comes in the rendering part. I can't figure out a way to display each and every todo in their own <TodoItems/>
component, and also when using forEach()
, nothing happens because I think that someone told me that setState()
works asynchronously.
I really need some advice!
Thanks...