Update an element in an array object at state by using textInput React Native

Viewed 12113

What I'm trying to do here is to update the array object 'available' using textInput and below is my code. I don't know why it keeps giving me the token error at the _update function line. Please help. Thank you!

export class Inventory extends Component {
state = {
    available: [
        {id: 0, name: 'Xb', value:5},
        {id: 1, name: 'Ad', value:19},
        {id: 2, name: 'Sc', value:1},
        {id: 3, name: 'AV', value:3},
        {id: 4, name: 'Ba', value:8},
        {id: 5, name: 'Ch', value:2},
        {id: 6, name: 'Pr', value:9},
        {id: 7, name: 'Mi', value:10},
        {id: 8, name: 'Se', value:1},
    ],
}

    _update = (text,index) => this.setState({available[index].value: text});

render(){
 index = 0;
  return(
    <View style={styles.container}> 
      <TextInput style={styles.input}
      keyboardType = 'number-pad'
      returnKeyType = 'go' 
      autoCapitalize = 'none'
      maxLength = {3}
      value = {this.state.available[index].value}
      onChange = {(text) => _update(text,index)} />
    </View>
  );
}
2 Answers

Never mutate this.state like you do it directly with the normal javascript way. Actually you should have in mind that this.state is immutable. The best way to go with this:

1- First create the copy of state array.

2- Find index of the item (if index is available skip this one).

3- Update the value of item at that index.

4- Use setState to update the state value. So in your case you would do something like:

 (text,index) => {
   let newArray = [...this.state.available];
     newArray[index] = {...newArray[index], value: text}
   this.setState({available: newArray});
  }

Hope this will help you out.

Related