Bpicks
Bpicks

Reputation: 31

How to set state of a nested array in React (Edited)

I have this set of data

this.state = { weeks: [ { weekNumber: 1, weights: [] }, { weekNumber: 2, weights: [] } ] }

What I want to do is create a new array and set it to 'weights'. I've checked other posts like this one: Set state of nested array

I assume I do something similar.

Edit: Also, say for instance I want to update each individual week's weights array, how would I go about doing that?

Upvotes: 0

Views: 278

Answers (2)

namth
namth

Reputation: 3107

I usually use this solution:

const newWeeks = [ ...this.state.weeks ];
newWeeks[0] = { ...newWeeks[0] };
//modify `newWeeks`

this.setState({
  weeks: newWeeks
});

Update 1: Live version: https://codesandbox.io/s/20v7r2zx0j?fontsize=14&module=%2Fsrc%2FTest.js


Update 2: thank @bird. Problem is Spread only goes one level deep when copying an array(or object), so we need an extra step here:

newWeeks[0] = { ...newWeeks[0] };

Upvotes: 1

tam.dangc
tam.dangc

Reputation: 2032

Because it's a nested object, then you can clone with native javascript code with JSON.parse(JSON.stringify(obj))

this.state = {
    weeks: [
        {
            weekNumber: 1,
            weights: []
        },
        {
            weekNumber: 2,
            weights: []
        }
    ]
}

const newWeeks = JSON.parse(JSON.stringify(this.state.weeks))

newWeeks[0].weights = [1,2,3]

this.setState({weeks: newWeeks})

The other normal clone like: [...this.state.weeks] or Object.assign([], this.state.weeks) only clone properties of level 1 not the nested, in your case, the weight property will not be cloned, just copied the reference in a normal way.

You can take a look at cloneDeep of lodash lib or use immer to archive your goal, also.

Upvotes: 0

Related Questions