Skip to content
Advertisement

How to update “prevState” in react.js? [closed]

I have got a list of array of objects. I want to update the state. When I click on the 1st item of the array, it’s giving isTrue: false, when I click on the second array of items, isTrue is given as true. I want to get 1st item isTrue:true, when I click on the second array of items that give isTrue: true. How can I do this?

Here is the link

import React, { Component } from "react";
import Child from "./child";
export default class App extends Component {
  state = {
    data: [
      { id: "2", name: "johan", org: "ORg" },
      { id: "1", name: "doe", org: "ORg" }
    ]
  };
  handleClick = e => {
    let newData = this.state.data.map(obj => {
      if (obj.id === e.target.id) {
        return { ...obj, isTrue: !obj.isTrue };
      } else {
        return { ...obj, isTrue: false };
      }
    });

    this.setState({ data: newData });
  };
  render() {
    return (
      <div>
        {this.state.data.map(item => (
          <Child data={item} key={item.id} handleClick={this.handleClick} />
        ))}
        {/* <Child data={this.state.data} handleClick={this.handleClick} /> */}
      </div>
    );
  }
}

Advertisement

Answer

You need more than one boolean in state to manage all of them. Update your data to be:

data: [
  { id: "name", name: "ss", org: "s", isTrue: true },
  { id: "nams", name: "ss", org: "s", isTrue: true }
]

Then add a name or id to your lis

<li id={item.id} onClick={this.handleClick}>{item.name}</li>

Then update your change handler to update the correct data object

handleClick = (e) => {
  // Map over old data and return new objects so we dont mutate state
  let newData = this.state.data.map(obj => {
    // If the ID matches then update the value
    if (obj.id == e.target.id) {
      return {...obj, isTrue: !obj.isTrue}
    }

     // else return the same object
     return obj;
  });

  // Update the state with the new object
  this.setState({ data: newData });
};
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement