tim
tim

Reputation: 208

How can I update the state of objects within an array using React?

What is the best practice in React to push a new object to an array within an object that doesn't have a key and then have the state update? I'm currently able to update it, but it's mutating the state which I know is not a best practice. I'd like to be able to use this.setState so my component re-renders. Thanks!

currentState = {
    lorem: [
        {
            id: 123,
            title: 'quis nostrud'
            ipsum: [
                {
                    dolor: 0,
                    amet: 0
                }
            ]
        },
        {
            id: 456,
            title: 'occaecat cupidatat'
            ipsum: [
                {
                    dolor: 0,
                    amet: 0
                }
            ]
        }
    ]
}

desiredState = {
    lorem: [
        {
            id: 123,
            title: 'quis nostrud'
            ipsum: [
                {
                    dolor: 0,
                    amet: 0
                },
                {
                    dolor: 100,
                    amet: 100
                }
            ]
        },
        {
            id: 456,
            title: 'occaecat cupidatat'
            ipsum: [
                {
                    dolor: 0,
                    amet: 0
                }
            ]
        }
    ]
}

Upvotes: 1

Views: 63

Answers (2)

Jon B
Jon B

Reputation: 2824

I have updated the code from @gdh above which was overwriting the lorem object with the new ipsum array.

Here is a working example that instead appends the new object to the correct ipsum array within the lorem object: https://codesandbox.io/s/cool-star-k8kpo?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 1

gdh
gdh

Reputation: 13682

Yes you should not mutate the original state directly. You need to find the id of which object you need to update in the array then update the state.

Like this

const updatedLorem = currentState.lorem.map(x => {
    if(x.id === '123') // <----- you will need to know which id to update
        return [...x.ipsum, {dolor: 0, amet: 0}]
    else
        return x
})

this.setState(prev => ({
    ...prev,
    lorem: updatedLorem
}))

Upvotes: 2

Related Questions