0

I have a promise from Fetch that I use to get the list of countries from our API:

async fetchDataFromAPI () {
    console.log('fetchDataFromAPI')
    let response = await fetch(process.env.NEXT_PUBLIC_BRIDGEMAN_API_URL + '/countries',
        {
            method: 'GET',
            headers: {
                'Content-Type': 'application/ld+json',
                'Accept': 'application/json'
            }
        })
    let data = await response.json();
    return data
}

I call that promise inside of a class component in componentDidMount:

componentDidMount() {
    this.setState({countries: this.fetchDataFromAPI()})
}

Then when I pass it to the render function, Like this:

const {
    countries
} = this.state

console.log('state countries', countries)

I get the following output in my console:

Promise { <state>: "pending" }
                <state>: "fulfilled"
                    <value>: Array(244) [ {…}, {…}, {…}, … ]
                        [0…99]
                        [100…199]
                        [200…243]
                        length: 244
                        <prototype>: Array []
                            <prototype>: Promise.prototype { … }

All the data is there in the ''. I just dont know how to get at it?

I've tried countries.then((data) => {console.log('data', data)}) but I get the message that countries has no method .then. I've tried countries.map and that is the same error.

How can I loop through and output the data on the page?

Richard Bridge
  • 318
  • 1
  • 3
  • 10
  • 1
    Put `await` while calling method `this.setState({countries: await this.fetchDataFromAPI()})` – Jaydip Jadhav Jan 25 '23 at 11:54
  • 1
    Async functions ALWAYS return a promise. So you need to await it's response like `wait this.fetchDataFromAPI()` – Reyno Jan 25 '23 at 11:55
  • See: [what is right way to do API call in react js?](https://stackoverflow.com/a/48353630) – Nick Parsons Jan 25 '23 at 11:59
  • @NickParsons I do use the fetch inside the componentDidMount, just like the link you sent me said – Richard Bridge Jan 25 '23 at 12:04
  • @RichardBridge No, you're doing it differently to what the link I sent suggests, the equivalent would be `this.fetchDataFromAPI().then((data) => this.setState({countries: data}))` – Nick Parsons Jan 25 '23 at 12:06

0 Answers0