I'm working on a React project where I have a list of tasks that are able to be "edited". My thought process is when the user clicks edit, it fills the form with the current tasks information, and when they click "save edit" it just finds the key at which the task is at, deletes it, then creates a new task with a new key, but all of the other information is the same. However, when I try this, it does not seem to work, and just deletes the task.
Heres a snippet, hopefully it helps:
var saveHandler = (e) => {
e.preventDefault();
props.seteId(props.editTask.id); //set the old task's key
props.setTasks([ //add our "edited" task to the list with the form info, and new key.
...props.tasks,
{
text: props.inputText,
status: props.status,
id: Math.random() * 1500, //I know this isnt a great way to do it
priority: props.priority,
},
]);
props.setTasks(props.tasks.filter((el) => el.id !== props.eId)); //find old task and delete it
State is updated asynchronously.
You're calling props.setTasks twice, but the value of props.tasks isn't changing between them so you are overwriting (not building on) the first state change you make.
Use a variable to store your intermediate state instead.
const allTasks = [ ...props.tasks, { /* etc */ } ];
const updatedTasks = allTasks.filter( /* etc */ );
props.setTasks(updatedTasks);
Likewise, props.eId won't have updated in time for el.id !== props.eId so use props.editTask.id instead of props.eId in your filter function.
If i wel understand your needs this should fix your issue, testing using the old id props.editTask.id
var saveHandler = (e) => {
e.preventDefault();
props.seteId(props.editTask.id); //set the old task's key
props.setTasks([ //add our "edited" task to the list with the form info, and new key.
...props.tasks,
{
text: props.inputText,
status: props.status,
id: Math.random() * 1500, //I know this isnt a great way to do it
priority: props.priority,
},
]);
props.setTasks(props.tasks.filter((el) => el.id !== props.editTask.id)); //find old task and delete it