React: Updating a value in state array

How to update just one value in an array of objects in a state

“Red and Blue Pelikan Br 40 Eraser on White Surface” by Pixabay

Say we have a component with an array of to-do's, just like this:

state = {
  todos: [
   {id: 1,
    title: "Eat breakfast",
    completed: false},
   {id: 2,
    title: "Make bed",
    completed: false}

How could we change the value of just key in just one object?

Step 1: Find the element

We first want to find the index in the array of the object, or where the object is located in the array. You can find the element by any key, id or name, or any other you find useful. We will use its id that e.g. we are getting from the function . Find the given element by its id and its index in the array (e.g. by using the method .findIndex())

const elementsIndex = this.state.todos.findIndex(element => []( == id )

Step 2: Create a copy of the state array

Because we should never modify directly the state, let’s create its copy through ES6 spread operator feature and let’s save it to a variable.

let newArray = [...this.state.todos]

Step 3: Update the one value

Here are our steps:

  1. Let’s redefine the one object we want to update using bracket notation for its index.

  2. Let’s create the copy of the object (spread operator again) and then rewrite the one value of the one key we want. In this case, we will switch the “completed” key from false to true and so we are using the ! to negate the current value.

    newArray[elementsIndex] = {...newArray[elementsIndex], completed: !newArray[elementsIndex].completed}

Note: While ‘todos’ is an array and that’s why the index matters, the individual toDoItem is an object and objects are unordered collections. Because of that, you can choose just one value out of order that will get updated.

Step 4: SetState

Pass newArr as a value of ‘todos’:

todos: newArray,

Continue Learning