SonOfNye
SonOfNye

Reputation: 75

Updating arrays that are part of a React state

I have a state that I have created and one of the properties of that sate is an array with an arbitrary number of values. Using setState functionality I can manipulate the array property in its entirety but what I want to do is dig into the property and change the Nth index of the array. I'm struggling with that and it almost seems like I need to just rebuild the whole array with whatever I want to change and then just swap the new array with the old one.

Upvotes: 0

Views: 97

Answers (2)

Shubham Patel
Shubham Patel

Reputation: 76

You can also try

let newArray = [...this.state.array].map((a, index) => {
    if (index === NthIndex) {
        return newValue
    }

    return a
})

this.setState({ array: newArray })

Upvotes: 1

Quentin
Quentin

Reputation: 944455

I'm struggling with that and it almost seems like I need to just rebuild the whole array with whatever I want to change and then just swap the new array with the old one.

Yes.

Provide a new value to the set state function, don't mutate the state variable.

setMyState(
    oldState.map((currentValue, index) => {
        if (index === Nth) {
            return newValue;
        } else {
            return currentValue;
        }
    })
)

Upvotes: 1

Related Questions