andi hakim
andi hakim

Reputation: 35

React push object into array, always pushed last array

i'm new on React Js things. already tried push object into array.

I already got the result using axios, but i can't push it to array.the result always return last array, F.ex : [0]: {channel:"esl_dota2", stream:null},[1]: {channel:"esl_dota2", stream:null},[2]: {channel:"esl_dota2", stream:null},[3]: {channel:"esl_dota2", stream:null},[4]: {channel:"esl_dota2", stream:null},

GetStream(){
var channels = ['comster404', 'freecodecamp', 'noobs2ninjas', 'esl_dota2', 'ESL_SC2'];
var temp = [];
var tempObj = {};

channels.map((i) => {
  axios({
    url: this.state.API_URL + i
  })
  .then(yeah => {         
    console.log(i);
    tempObj.channel = i;
    tempObj.stream = yeah.data.stream;      
    temp.push(tempObj);               
  })
  .catch(oops => {
    console.log(oops.status);
  });
});

console.log(temp);}

Upvotes: 0

Views: 1226

Answers (3)

m.rohail.akram
m.rohail.akram

Reputation: 350

You are adding tempObj to temp array on each iteration and changing value of tempObj as well.

So by reference you are updating value of each item because all items of array point to same object.

Upvotes: 1

Aniruddha Shevle
Aniruddha Shevle

Reputation: 4919

Just declare var tempObj = {}; inside your map method. That will help you.

Upvotes: 0

Giang Le
Giang Le

Reputation: 7054

Try unshift() instead push() to adds item to front of array

Upvotes: 0

Related Questions