1

How to use response from fetch api?

i try to return my response, but when i try to print this values in my function, i get undefined, can someone tell me how to use this response in different function?

my response is an json of nested objects

  async fetchData() {
    const url = `...`;

    fetch(url, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
            //
        })
    }).then((response) => response.json())
      .then(response => {;
        console.log(response) //correct response
        return response;
      })

  }

  async getDataFromFetchApi() {
      const data= await this.fetchData();
      console.log(data); // undefined

      if(data != undefined){
        throw new BadRequestException();
     }

      return data;   
  }

thanks for any help

  • Does this answer your question? [How can I return the fetch API results form a function?](https://stackoverflow.com/questions/51417108/how-can-i-return-the-fetch-api-results-form-a-function) – Harmandeep Singh Kalsi Aug 16 '20 at 16:35

2 Answers2

1

Bottom line, an async function must return a promise to work correctly. fetchData has no return value. The return response is inside of a .then, and doesn't apply to the fetchData function itself.

For the above code, the fewest modifications is simply to return fetch(...) in your fetchData function, like this:

async fetchData() {
  const url = `...`;

  return fetch(/* ... */)
    .then((response) => response.json())
    .then(response => {
      console.log(response) //correct response
      return response;
    })

}

Alternatively you could use the async/await syntax for all it's worth, and get rid of your .thens, like this:

async fetchData() {
  const url = `...`;

  const resp = await fetch(/* ... */);
  const json = await resp.json();
  console.log(json);
  return json;
}
David784
  • 7,031
  • 2
  • 22
  • 29
0

You have to return data in the scope of fetchData function:

async fetchData() {
    const url = `...`;

    const response = await fetch(url, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
            //...
        })
    });

    return response;
}
TTY112358
  • 134
  • 6