0

Is there a way I could setState with arrays?

this.state={
numberOne:'',
numberTwo:'',
numberThree:'',
}
this.setState({numberOne:1})
this.setState({numberTwo:2})
this.setState({numberThree:3})

The code above will work but the code below wouldn't.

this.state={
numbers:['','','']
}

this.setState({numbers[0]:0})
this.setState({numbers[1]:1})
this.setState({numbers[1]:1})

How to I setState with arrays?

2
  • I don't know about React Native, but in ReactJS we can use spread operator. like setState({numbers: ...numbers}) ; Commented Aug 1, 2018 at 9:09
  • Possible duplicate of How to use an array with setState? Commented Aug 1, 2018 at 9:13

2 Answers 2

2

You can do it as follows:

this.setState({ numbers: [1, 2, 3] })

Or if you want to edit a specific array index, then you have to create a new copy of the array, without mutating the state:

const copied = [...this.state.numbers]
copied[0] = 1
this.setState({ numbers: copied })

Keep in mind that the copying can be done by value or reference, according to the array values types.

For booleans, strings, numbers array values it's is done by value (deep copying) and mutating the copied array values won't affect the origin one's values. So if this is your case - then you should not be worried about.

For objects array values - the copying is done by reference (shallow copying) and you have to be careful to not mutate the original array incidentally. You can read more about the array copying here.

In short: Whatever approach you take, always make sure you don't mutate the origin (state) array.

Sign up to request clarification or add additional context in comments.

Comments

0

That syntax makes no sense. And you can't mutate the state directly. For changing individual array elements or object properties, you need to copy that state property first, modify that value, then replace the entire property. E.g:

// Initial state in constructor
this.state = { numbers: [1,2,3] };

Then to change it somewhere:

let newNumbers = this.state.numbers.slice(0); // makes copy of the array
newNumbers[1] = 5;
this.setState({numbers: newNumbers});

and then you state will be { numbers: [1,5,3] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.