Home > Net >  React updating a state array that is nested within array of objects
React updating a state array that is nested within array of objects

Time:12-07

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.

CodePudding user response:

You can use the spread operator and Array.prototype.map() to update the nested array:

const handleOnClick = (bodyPart) => {
    setParts(
        parts.map((part) => {
            if (part.bodyPart === bodyPart){
                return {
                    ...part, 
                    active: [
                        ...part.active.slice(0, option), 
                        true,
                        ...part.active.slice(option   1)
                    ]
                }
            } else {
                return part;
            }
        })
    )
}

  • Related