Skip to content

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

Open

Description

@edzhuang

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.

Activity

  1. changed the title [-]Challenge Solution in "Updating Arrays in State" Uses Mutation[/-] [+]Challenge Solution in "Updating Arrays in State" Page Uses Mutation[/+] on Mar 13, 2023
  2. ferrybig commented on Mar 17, 2023

    @ferrybig

    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

  3. jaisaichand commented on May 1, 2023

    @jaisaichand

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

  4. Ashish-simpleCoder commented on May 7, 2023

    @Ashish-simpleCoder

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

  5. rickhanlonii commented on Jan 24, 2024

    @rickhanlonii
    Member

    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.

  6. rickhanlonii commented on Jan 24, 2024

    @rickhanlonii
    Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions