Thanh Pham
Thanh Pham

Reputation: 61

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

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>
  );
}

Upvotes: 4

Views: 13875

Answers (2)

Brianhenry
Brianhenry

Reputation: 189

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.

Upvotes: 2

hyb175
hyb175

Reputation: 1291

_update = (text,index) => this.setState({available[index].value: text}); is not valid in a few ways. First, setState takes an object that should be the same key and value that is on your state right now if you are updating the value. Second, available[index].value does not evaluate to anything because available is not defined. You can only access available via this.state.available. Third, available[index].value is gonna be the key on the new component state, which is not what your desired I presume.

Change your update to be something like this

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

Upvotes: 9

Related Questions