0

How do you setState an object and an array at the same time after passing id and data to a function? Because comment is not part of an array, I'm getting confused.

this.state = {
      tasks: [
        { firstName: "boris", lastName: "Johnson", id: uuid() },
        { firstName: "Mary", lastName: "Whithaker", id: uuid() }
      ],
      comment: "This is a comment message"
    };

  updateTask(id, task, comment, additional) {
    const updatedProject = this.state.tasks.map(t => {
      if (t.id === id) {
        return {
          ...t,
          firstName: task,
          lastName: comment
        };
      }
      return t;
    });
    this.setState({ tasks: updatedProject, comment: additional });
  }
edelcodes
  • 67
  • 7

1 Answers1

1

Your State is an object. In that object there are two fields, tasks and comment. Tasks is an array of objects, those objects have firstname, lastname and id fields. Comment is a string.

When that code is doing setState at the end, it is creating a new object (see the {}), and then giving it the updatedProject array for tasks, and then the additional string for comment.

That whole object is then set. The array and string are values of fields in that object.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
  • From an object standpoint, yes. But it is generally good practise in React to not use the previous `this.state` to calculate the new state, as it is async and may be out of date. Give setState a method instead, see https://stackoverflow.com/a/48209870/13892264 – Luke Storry Jul 25 '20 at 22:50