Home > Enterprise >  How to change multiple Boolean values()Parent Item, Child Item) in an array on click
How to change multiple Boolean values()Parent Item, Child Item) in an array on click

Time:10-18

I am working in a task where I need to change the Boolean values onclick from an array of items, I need to change the Boolean value from array and child array. I have changed the value from an array it's working as expected but inside that array I am having an another array of objects from that I need to change the boolean value. OnClick I need to make parent isProcessing and child isProcessing false. I have tried changing it but I am not getting the expected output , can anyone guide me how to achieve this thanks in advance.

Mock Data:

const mockItems = [
  {
    id: '1',
    itemType: 'metal',
    doneBy: {
      id: '1',
      display: 'Item Name',
    },
    catg: 'A',
    createdDate: '01/01/2021',
    updatedBy: {
      id: '1',
      type: 'M-A',
    },
    isProcessing: 'true',
    subItems: [
      {
        id: '1',
        doneBy: {
          id: '1',
          display: 'sub item name',
        },
        status: {
          type: 'notapproved',
        },
        isProcessing: 'true',
      },
    ],
  },
];

Code for accessing parent : isProcessing //it's working

const [processingItem, setProcessingItem] = useState(mockItems);

const handleToggle = () => {
  setProcessingItem((prevState) =>
    prevState.map((prItem, i) =>
      i === 0 ? { ...prItem, isProcessing: false } : prItem
    )
  );
};

//code to change child array Boolean not working

const handleToggle = () => {
  setProcessingItem((prevState) => {
    prevState.map((prItem, index) => {
      if (index === 0) {
        const obj = { ...prItem.subItems, isProcessing: false };
        return { ...prItem, isProcessing: false, obj };
      }
    });
  });
};

CodePudding user response:

Try this

const handleToggle = () => {
        setProcessingItem((prevState) => {
            prevState.map((prItem, index) => {
                if(index !=0)
                return prItem;
                const subItems = prItem.subItems.map((si,idx)=>{
                    return idx != 0 ? si : {...si,isProcessing: false}
                });
                return { ...prItem, isProcessing: false, subItems:subItems }
            }
            )
        }
        )
    }
  • Related