Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  13] [ 4]  / answers: 1 / hits: 17321  / 6 Years ago, sun, september 2, 2018, 12:00:00

I have two functions and when I press each of them I create an array.



    this.state = {
food:[],
sports:[],
interest:[],
}

_favoriteFood(foodState){
const food = foodState
this.setState({food:food})
console.log(food)
console.log(this.state.food)
}

_favoriteSports(SportsState){
const sports = SportsState
this.setState({sports:sports})
console.log(sports)
console.log(this.state.sports)
}
render(){


return (
<View>
<FavoriteFood favoriteFood={this._favoriteFood}/>
</View>
<View>
<FavoriteSports favoriteSports={this._favoriteSports}/>
</View>
)}


So for example, I am getting arrays like food:[pizza, hodog] and sports:[basketball, surfing] when I call a method by pressing a button.



My question is when I try to merge two arrays like:



const interest = [...this.state.food, ...this.state.sports]


Its showing undefined because I think I am calling it before the render happens.



Should I make another method to merge arrays?
Any advice or comments would be really helpful. Thanks in advance :)


More From » arrays

 Answers
22

You problem can happen because React doesn't change the state immediately when you call setState, it may change the state later. If you want to access the state after React applies the change, you should use the second argument of the setState method:



_favoriteFood(food){
this.setState({food}, () => {
const interest = [...this.state.food, ...this.state.sports];
});
}


Reference



The other solution is to use your method argument instead of reading the same value from this.state:



_favoriteFood(food){
this.setState({food});
const interest = [...food, ...this.state.sports];
}


BTW, you should not store const interest = [...this.state.food, ...this.state.sports] in the state, because it can be derived from the other state variables.


[#53583] Wednesday, August 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchell

Total Points: 95
Total Questions: 110
Total Answers: 87

Location: Gabon
Member since Thu, Jul 15, 2021
3 Years ago
;