Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Promise.all challenge

I have a situation where I make three fetch calls. Every fetch calls has a callback function which will update the respective property of state.twitterfeed object and finally setState. Issue is that it is calling the setState 3 times as of now. My aim is to use promise.all and update setStatus only once. I tried multiple times but its confusing and challenging.

Code:

this.state = {
  twitterfeed: {
    techcrunch: [],
    laughingsquid: [],
    appdirect: []
  }
}

updateTwitterFeed = (data, user) => {
  const twitterfeed = { ...this.state.twitterfeed
  };
  if (user === "appdirect") {
    twitterfeed.appdirect = data;
  } else if (user === "laughingsquid") {
    twitterfeed.laughingsquid = data;
  } else {
    twitterfeed.techcrunch = data;
  }
  this.setState({
    isloadcomplete: true,
    twitterfeed
  });
};

componentDidMount() {
  fetch(
      "http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=techcrunch"
    )
    .then(response => response.json())
    .then(data => this.updateTwitterFeed(data, "techcrunch"));

  fetch(
      "http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=laughingsquid"
    )
    .then(response => response.json())
    .then(data => this.updateTwitterFeed(data, "laughingsquid"));

  fetch(
      "http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=appdirect"
    )
    .then(response => response.json())
    .then(data => this.updateTwitterFeed(data, "appdirect"));
}
like image 644
Vignesh Veeran Avatar asked Dec 12 '25 17:12

Vignesh Veeran


1 Answers

You should have a look at the documentation: Promise.all()

Promise.all() actually preserves the order for its returned values.

Hence you could have:

const promises = [];
promises.push(fetch("http://localhost:7890/1.1/statuses/user_timeline.json?count =30&screen_name=techcrunch"));
promises.push(fetch("http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=laughingsquid"));
promises.push(fetch("http://localhost:7890/1.1/statuses/user_timeline.json?count=30&screen_name=appdirect"));
// Execute all promises
Promise.all(promises).then(values => {
    console.log(values);
    const twitterfeed = { ...this.state.twitterfeed};
    twitterfeed.techcrunch = json.parse(values[0]);
    twitterfeed.laughingsquid = json.parse(values[1]);
    twitterfeed.appdirect = json.parse(values[2]);
    this.setState({
        isloadcomplete: true,
        twitterfeed
    });
});
like image 187
Mederic Avatar answered Dec 15 '25 07:12

Mederic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!