react.dev icon indicating copy to clipboard operation
react.dev copied to clipboard

Challenge Solution in "Updating Arrays in State" Page Uses Mutation

Open edzhuang opened this issue 1 year ago • 5 comments

For the solution to the third challenge in the Updating Arrays in State page, it uses the following function:

function handleAddTodo(title) {
  setTodos([
    ...todos,
    {
      id: nextId++,
      title: title,
      done: false
    }
  ]);
}

This changes nextId, a variable outside the component's scope, which I believe is a mutation. It should instead use the length of todos to set the next id.

edzhuang avatar Mar 13 '23 01:03 edzhuang

Using the length of the array becomes unsafe if you are also going to implement deletion.

You could go to the last items and add 1 to the id, but this also breaks when you add a sorting function

In react, event handlers are allowed to have side effects, so the side effect of mutating the global counter is safe

ferrybig avatar Mar 17 '23 09:03 ferrybig

Pls assign this to me, I would like to work on this if no one is currently working on it

jaisaichand avatar May 01 '23 18:05 jaisaichand

We can also try using the Date.now().toString() as value for the id attribute. It will always be unique and safe.

Ashish-simpleCoder avatar May 07 '23 12:05 Ashish-simpleCoder

Yeah, the mutation is ok because it's mutating a module level variable in a click handler. But since this is teaching you to not mutated, it would be good to include a note in the solution that explains why mutating the nextId is OK.

rickhanlonii avatar Jan 24 '24 05:01 rickhanlonii

If you're interested in improving it, please just submit a PR, we don't assign issues.

rickhanlonii avatar Jan 24 '24 05:01 rickhanlonii