Reputation: 541
Doing this:
onPress={() => {
this.setState({
myArray: []
});
const { myArray } = this.state;
console.log(myArray);
}}
Expect the array to be empty, but it still contains old values. If I press the button again, or console.log at a different place in the program, the array is empty. I take it this is due to this.state being asynchronous. This is a problem since, instead of the console.log, I'm planning to have the array saved to AsyncStore
like this:
AsyncStorage.setItem(
"@ShoppingListStore: ShoppingListKey",
JSON.stringify(myArray)
);
If I can't save the array directly after the state has been set, where can I do it? Is there a way to listen for the state to complete setting, then run the AsyncStore code?
Upvotes: 0
Views: 27
Reputation: 1740
Try something like that:
onPress={() => {
this.setState({
...this.state, myArray: []
}, () => console.log(this.state.myArray));
}}
Upvotes: 1