0

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
        }))
      }
    ]);
  };
0

1 Answer 1

1

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
        )
    );
  };

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.