4

I have an array in my state:

state = {
  some_array: [1,1,1,3,6,3,6,23], // sorry for the syntax it's changed
 }
 
 

Now I want to change value in that array that has index let's say 4, and in this case that would be number 6, or if I want to change index 1, that would be second number or array.
I know this is probabbly very simple but I'm just very confused.

If you need more info please comment.

Thanks!

crodev
  • 1,323
  • 6
  • 22
  • 39
  • 3
    Just do `state.some_array[indexHere] = newValue` – brk Aug 29 '18 at 14:15
  • 1
    Shouldn't I use this.setState()? – crodev Aug 29 '18 at 14:18
  • @brk [react-docs](https://reactjs.org/docs/react-component.html#state) says Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable. – Taxellool Aug 29 '18 at 18:05

1 Answers1

10

I think that you can to use next code:

const some_array = [...this.state.some_array]
some_array[indexHere] = yourValue
this.setState({some_array:some_array})

This example --- true way for FP in react.

Petrashka Siarhei
  • 733
  • 10
  • 12