0

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);}
Community
  • 1
  • 1
andi hakim
  • 35
  • 7

3 Answers3

1

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.

m.rohail.akram
  • 350
  • 1
  • 11
0

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

Giang Le
  • 6,446
  • 4
  • 23
  • 26
0

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

Aniruddha Shevle
  • 4,602
  • 4
  • 22
  • 36
  • Perfect. can u little bit describe why previos code didn't work? – andi hakim May 11 '17 at 12:21
  • Firstly Object and Array are referenced type. You've declared tempObj in the local scope at the start. So if you console it after the map method, it'll give you last values stored in tempObj ie {channel:"esl_dota2", stream:null} because of the same keys. As Array is the referenced type, it'll have the values as that of tempObj does ie {channel:"esl_dota2", stream:null} locally. If you declare and initialize tempObj inside map method, for the 1st run, tempObj will store 1st key & value pairs and push it in the array then in the 2nd run tempObj will be **reinitialize** to empty again and so on.. – Aniruddha Shevle May 11 '17 at 13:30