Home > Mobile >  Update boolean value based on previous state React JS
Update boolean value based on previous state React JS

Time:10-14

I am trying to update the Boolean value based on previous state in onClick. I am having three values in the mock, the mockdata structure is it's having array of object. I am having 3 items in that array of object , in that I am trying to loop all three items and for the first element in the list I am trying to update the Boolean value from true to false, I have tried multiple ways to achieve this but all the implementation got failure, I have searched in many forum and youtube channels all are explaining for the counter which is incremented by 5. I am not getting any examples which takes array of object in it's state and getting the previous value. When I am trying to access one element from the item directly it's working but when I am trying to loop and select the first element I am not getting the desired output. Any body can help me how to achieve this. Thanks in advance.

Mock Data:

const employeeData = {
  employees: [
    {
      id: "112",
      isCreated: true,
      status: {
        type: "NA"
      },
      Date: {
        DOJ: "--"
      }
    },
    {
      id: "113",
      isCreated: true,
      status: {
        type: "NA"
      },
      Date: {
        DOJ: "--"
      }
    },
    {
      id: "114",
      isCreated: true,
      status: {
        type: "NA"
      },
      Date: {
        DOJ: "--"
      }
    }
  ]
};

Component:

  const [processingEmployees, setProcessingEmployees] = useState(
    employeeData.employees
  );

  //Direct Implementation this is working fine
  const onClick = () => {
    const employeeData = [...processingEmployees];
    employeeData[0].isCreated = false;
    setProcessingEmployees(employeeData);
  };

PrevState Implementation

  const onClick = () => {
    setProcessingEmployees((prevState) => [
      {
        ...prevState,
        EmpData: prevState.map((Employee) => ({
          ...Employee,
          isCreated: false
        }))
      }
    ]);
  };

CodePudding user response:

Try this approach. Map over prevState, if the index of the item is zero, create a new object from the item, changing isCreated to false. Otherwise leave the item alone.

  const onClick = () => {
    setProcessingEmployees((prevState) => 
        prevState.map((emp, i) => 
          i === 0 
          ? {...emp, isCreated: false}
          : emp
        )
    );
  };

  • Related