react native how to merge two arrays with a function
Solution 1
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];
});
}
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.
Solution 2
Push multi item in array
Merge Two Array
var subject1=['item1','item2']
var subject=['item3','item4','item5'];
subject1.push(...subject)
console.log(subject1);
//output
['item1', 'item2', 'item3', 'item4', 'item5']
kirimi
Updated on July 18, 2022Comments
-
kirimi almost 2 years
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]
andsports:[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 :)
-
kirimi over 5 yearsthank you very much it works great. In the console now I see the merged arrays.
-
kirimi over 5 yearsbut how would I call merged arrays inside the
render() {return()}
? -
Finesse over 5 years@kirimi Inside
render
this way:const interest = [...this.state.food, ...this.state.sports];
. Therender
method must be able to render any possible component state so make anif
statement that renders something else when the value is undefined. -
Finesse over 5 years@kirimi Or add a default value for the state item. According to your question, neither
this.state.food
northis.state.sports
can be undefined in any moment of time (if the methods are given values).