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);}
0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Perfect. can u little bit describe why previos code didn't work?
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..
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.