0

When I try to set my state with the returned values I get from stories, I receive an array full of Promises with their status and value.

(30) [Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise]
0: Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object

image from my console.log on render

How do I only assign the data from the PromiseValue?

import React, { Component } from "react";
import axios from "axios";

class News extends Component {


state = {
  loading: true,
  data: null
};

async componentDidMount() {
  const ids = await axios.get(
    'https://hacker-news.firebaseio.com/v0/beststories.json?print=pretty&orderBy="$key"&limitToFirst=30'
  );

  const stories = await ids.data.map(id => {
    return axios.get(`https://hacker-news.firebaseio.com/v0/item/${id}.json`);
  });

  this.setState({ data: stories });
}

render() {
  console.log(this.state.data);
  const news = this.state.loading ? "Loading" : "News";
  return <div>{news}</div>;
}

}

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Devon Deason
  • 125
  • 2
  • 8

1 Answers1

3

Use Promise.all to get a single Promise that resolves with an array of values once every Promise in the array has resolved:

const storyPromises = ids.data.map(id => {
  return axios.get(`https://hacker-news.firebaseio.com/v0/item/${id}.json`);
});

const stories = await Promise.all( storyPromises );

this.setState({ data: stories });
Paul
  • 139,544
  • 27
  • 275
  • 264