React Beginner
React Beginner

Reputation: 87

Extract response data array from fetch function with post method

I've written an async function which is able to get a response from an API I've written in Python but I can't get the data into an array which I can then use to update my frontend application.

The code is as follows:

async function postData(URL) {
  let rawResponse = await fetch(URL, {
    method: "Post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(inputData),
  });
  const data = await rawResponse.json();
  console.log(data);
  return data;
}  

let response1 = postData();
console.log(response1);

let response2 = postData()["returnedData"];
console.log(response2);

The code returns the array I want when I console.log the data variable within the function. However, it returns an array called 'Promise{pending}'* for response1 which contains the desired data but I am not able to manipulate it and returns 'undefined' for response2. What am I doing wrong?

Thanks in advance!

*pending even though the PromiseState is 'fulfilled'

Upvotes: 2

Views: 1322

Answers (1)

Heet Vakharia
Heet Vakharia

Reputation: 445

PostData Function is a aync Function so returns a Promise so you must use await before calling it or .then

async function postData(URL) {
  let rawResponse = await fetch(URL, {
    method: "Post",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(inputData),
  });
  const data = await rawResponse.json();
  console.log(data);
  return data;
}
// Method 1
const init = async () => {
  let response1 = await postData();
  console.log(response1);

  let response2 = await postData()["returnedData"];
  console.log(response2);
}
init();
// Method 2
(async () => {
  let response1 = await postData();
  console.log(response1);

  let response2 = await postData()["returnedData"];
  console.log(response2);
})()
 

Upvotes: 2

Related Questions