I am trying to increment the ID value useing the useState hook,but its not incrementing .I have to call the fct two times for the id to be incremented.I was able to see that by console log the object before and after the usestate but i found the result the same
function ToDoListApp() {
const [noteList, setNoteList]=useState([])
const [note,setNote]=useState({ noteId: 0 , txt: "", noteState: false })
function addToList(e) {
e.preventDefault();
if(noteList.length===0){
console.log(note)
setNote({noteId: 0 , txt: note.txt ,noteState: false })
setNoteList(noteList=>[...noteList,note])
}else{
console.log(note)
console.log(noteList[noteList.length-1].noteId + 1)
setNote({noteId:noteList[noteList.length-1].noteId + 1,txt:note.txt, noteState:false})
setNoteList(noteList=>[...noteList,note])
console.log(note)
}
}
function deleteItemFromList(e,id){
setNoteList(noteList.filter(note => note.noteId !== id ))
console.log(noteList.length)
}
function handleTheNoteTxt(e) {
e.preventDefault();
setNote({
...note,
txt:e.target.value
})
}
const notesDiplay =noteList.map((note)=>
<Stack key={note.noteId} direction="row" className="note-styling" justifyContent="center" alignItems="center" spacing={2}>
<p>{note.txt} </p>
<p>{note.noteId} </p>
<Button onClick={e => deleteItemFromList(e,note.noteId)} variant="outlined" size='small' >X</Button>
</Stack>
)
return (
<div>
<Stack direction="column" justifyContent="center" alignItems="center">
<Stack className='note-app-container bg1' direction="column" justifyContent="flex-start" alignItems="center" spacing={2} >
<div className='notes-input bg3'>
<TextField autoFocus label="Add your note" variant="standard" value={note.txt}
onChange={handleTheNoteTxt}/>
<Button variant="outlined" size='medium' onClick={addToList}>Add</Button>
</div>
<div className='notes-container bg3'>
{notesDiplay}
</div>
</Stack>
</Stack>
</div>
)
}
export default ToDoListApp`