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>
);
}
_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 });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With