const [addData,setAddData]=useState({
title:"",
state:"incomplete",
index:0
})
function handleAddPage(event){
setAddData((prev) =>{
return {...prev,[event.target.name]:event.target.value}
})
}
function AddHandler(event){
event.preventDefault();
const uniq=uuid();
setAddData((prev)=>({
...prev,[state]:uniq
}));
setAll([...all,addData]);
if(addData.state==="complete")
setComplete([...complete,addData]);
else if(addData.state==="incomplete")
setIncomplete([...incomplete,addData]);
}
I am trying to pass unique id’s with each task.But , 0(default) is being allocated to each task.
2
Answers
The issue you are facing is due to the asynchronous nature of the state updates in React. When you call
setAddData
to update theaddData
state with the unique ID, theaddData
state has not yet been updated with the new value when you add it to the arrays (all
,complete
,incomplete
).Here’s my solution.