0

This is what I have in the state variable

this.state = {
            check: 0,
            places: ["0","0","0","0","0","0","0","0"],
    }
  }

What I am trying to do is call a function to update desired value of a location. For example, I'm using changeValue function like this:

changeValue= (event) => {

        this.setState({
            places[2]: "1",
        });
  }

And it's not working. I know I can pass a fully updated array but I need the other values of the current state.

DiegoS
  • 816
  • 1
  • 10
  • 26
ShocKwav3_
  • 1,670
  • 6
  • 22
  • 44
  • This answer should help: http://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle – Matt D. Webb Mar 11 '17 at 22:56

3 Answers3

1

Here's how you get the rest of the current places array (and copy it to ensure you don't mutate the state outside setState):

changeValue = (event) => {
  const places = this.state.places.slice();
  places[2] = '1';
  this.setState({ places });
}
James Ganong
  • 1,160
  • 8
  • 15
0

Add this line to your constructor.

this.changeValue = this.changeValue.bind(this);

In addition to the other answer here, you'll also need to bind the function in the constructor for it to work, especially if you're trying to handle the event via a callback from the child.

Arvind
  • 730
  • 10
  • 20
0

setState take object as an argument with key as state key. make sure you pass the right key to update the state.

Try this--->

changeValue= (event) => {
        this.setState({
            places: places.map((item, index) => { 
                            if(index == 2) return 1;
                            return item;  
                    });
        });   }
Khalid Azam
  • 1,615
  • 19
  • 17