Search code examples
reactjslodashsetstate

How to use Lodash to find a specific item in an array and then use setState() to update it?


Add a new method adopt() to the App component that takes in the name of a pet (a String), and modifies the Object representing that pet in the pets state variable so that the pet's adopted property becomes true.

- Because this function will be called from an event handle, you'll want to define it as a _public class field_. Alternatively, you can wrap it in an arrow function when specified as a callback.

- Since you'll be wanting to modify elements in the state _based on_ the current state, you'll need to call the **`setState()`** method and pass it an (anonymous) callback function. This function should expect a parameter representing the current `state` and do the following:

    1. Then locate the correct pet Object inside the current `state.pets` array (the lodash [`.find()`](https://lodash.com/docs/4.17.10#find) function can help. Look at the examples for how you can find an object that has a particular property, such as the `name`).

    2. Assign a new value to that object's `adopted` property, indicating the pet is adopted.

    3. `return` an Object of values to change in the state—namely, that the `pets` value should now have the updated `state.pets` value.

Here is what I have tried but I don't get how to combine the two features

 adopt(petName) {
    this.setState(() => {
      let pet = _.find(this.state.pets, ['name', petName]);
      return {
        adopted: true
      };
    });
  }

Solution

  • It's much easier if you use findIndex

    adopt(petName) {
       this.setState(() => {
         let petIndex = _.findIndex(this.state.pets, ['name', petName]);
         pets[petIndex]={...pets[petIndex],adopted:true}}
         return this.state.pets
       });
     }