react native how to merge two arrays with a function

Viewed 15575

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 :)

2 Answers

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.

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']
Related