1

I have come around this topic today.

I am trying to map an array and update it like this.

 const editTask = (id, newTitle) => {
    const updatedTodo  = [...tasks].map(task => {
      task.id === id ? {...task, title: newTitle} : task
    });
    setTasks(updatedTodo);
  };

tasks is array of objects

One of my friends have told me that there is no need to copy the original array during map. because map itself returns the new array.

But as far as I know this array is considered as 2 level deep array and it needs to copy the original array too for the update of the object.

Can someone explain to me which way is correct and which is not? I am lost.

Thanks in advance

1 Answer 1

1

Your friend is right: map DOES return a new array (unlike forEach)

Since you're using react-hooks, creating a new array for the updated tasks is considered redundant and the best way to achieve the same result is to do something like this:

const editTask = (id, newTitle) => {
  setTasks((tasks) =>
    tasks.map((task) => (task.id === id ? { ...task, title: newTitle } : task))
  );
};
Sign up to request clarification or add additional context in comments.

2 Comments

If the solution worked for you, consider clicking the "check" icon. It'll help others with the same issue to identify the working solution.
I will be able to do it in 3 minutes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.