React updating a state array that is nested within array of objects

85 Views Asked by At

So I'm feeling somewhat confident on updating the array of objects when it's just array of objects using map and the spread function. However, where I'm stuck on is updating an array that is within array of objects.

Here's the example.

I have a seperate state to choose which index

const [option, setOption] = useState(0);

I initialize the state with array of objects

    const [parts, setParts] = useState([
        {bodyPart: "upperLip", price: 1000, active: [false, false, false]},
        {bodyPart: "chin", price: 1000, active: [false, false, false]},
    ])

Basically, I want to update the array that is nested in array of objects when the description of bodyPart matches up.

    const handleOnClick = (bodyPart) => {            
        
        parts.map((part) => {
            if (part.bodyPart === bodyPart){
                return {...part, active[option]=true}
            } else {
                //do nothing
            }
        })
    }

I know that return {...part, active[option]=true} part is incorrect. What would be the proper way of updating this piece within the state?

I've tried to set it to true like I would for an array, but I'm not too sure anymore.

1

There are 1 best solutions below

0
Hatim Tekri On
  1. update state using setParts function

  2. your handleOnClick function would be like this

     const handleOnClick = (bodyPart) => {            
       setParts((prevState) => {
    
        //find Index of given bodyPart
    
        const elementIndex = prevState.findIndex((ele) => ele.bodyPart 
          == bodyPart); 
    
        // updating data at that particular Index
        prevState[elementIndex] = {
    
        ...prevState[elementIndex],
        active: [
          ...prevState[elementIndex]. active,
         //adding new active option in that particular bodyPart
         option
         ],
       };
       return prevState; // return the updated data
     }); 
    
    }
    

Explaination of handleOnClick function

  • find Index value based on bodyPart value

  • update that particular Index element

    • add all the values in that Index element using spread operator

    ...prevState[elementIndex]

    • Edit active property inside that element and assign existing value to it using spread operator

    ...prevState[elementIndex]. active

    • just add new value in active property using comma

    active: [ ...prevState[elementIndex]. active, option ],

    • return the data at the end, means your are returning updated array

    return prevState;