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?

kirimi
  • 1,370
  • 4
  • 32
  • 57
  • I don't know about React Native, but in ReactJS we can use spread operator. like setState({numbers: ...numbers}) ; – Jagdeesh Kumar Aug 01 '18 at 09:09
  • Possible duplicate of [How to use an array with setState?](https://stackoverflow.com/questions/41131119/how-to-use-an-array-with-setstate) – RIYAJ KHAN Aug 01 '18 at 09:13

2 Answers2

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.

Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
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] }

Jayce444
  • 8,725
  • 3
  • 27
  • 43