2

How do I get my getData() function to actually return the data. At the moment I get a console log of a promise object

function getData() {
    fetch('//some api url')
        .then(response => response.json())
        .then(data => { return data })
};

export const data = getData();
console.log(data); // returns promise, not actual object
1
  • 5
    I'm not sure how you're getting a promise. You should be getting undefined. Commented Aug 15, 2022 at 16:04

1 Answer 1

1

You can't just wait for asynchronous code without await

function getData() {
  return fetch('//some api url')
    .then(response => response.json())
    .then(data => {
      return data
    })
};

getData().then(console.log)

function getData() {
  return fetch('//some api url')
    .then(response => response.json())
    .then(data => {
      return data
    })
};

(async () => {
  const data = await getData()
  console.log(data)
})()

Sign up to request clarification or add additional context in comments.

9 Comments

What is the point of .then(data => { return data }) in your answer?
for the first solution, is there any way I can export the data out to a variable like 'data' and then use export const data to use it on another page in react js
You can try this but I'm not sure if it works in the browsers
@mathsnerd22 you should await for fetchData()
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.