I have a class constructed as follows -:
constructor(props) {
super(props);
this.state = {
name: '',
guestsStore:[],
};
}
And I have a form that takes a text input and that is supposed to add the submitted name to the guestsStore array by calling this.handleNameSubmit
The following code doesn't work even if I have seen it in multiple code examples. It updates state but with an empty object-:
handleNameSubmit = (name) => {
this.setState({
guestsStore: [...this.state.guestsStore, name],
});
};
The following code works and updates state with the name.
handleNameSubmit = (name) => {
this.setState({
guestsStore:[...this.state.guestsStore, {name:this.state.name}],
})
}
I am new to React Native and would like to understand why this happens. Why in this case does the first code example fail even if it works in so many other cases
handleNameSubmit?nameget passed tohandleNameSubmit? How ishandleNameSubmitcalled? Also, not an answer to your question but you shouldn't usethis.stateinsetStatebecause updating of state can be deferred and create unexpected results, use "prevState". ie.this.setState((prevState, props) => ...