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 Answers1

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)
})()
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • What is the point of `.then(data => { return data })` in your answer? – Andy Aug 15 '22 at 16:08
  • [Is ".then(function(a){ return a; })" a no-op for promises?](https://stackoverflow.com/q/41089122) – VLAZ Aug 15 '22 at 16:13
  • 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 – mathsnerd22 Aug 15 '22 at 16:14
  • You can try [this](https://stackoverflow.com/a/56262272/5089567) but I'm not sure if it works in the browsers – Konrad Aug 15 '22 at 16:19
  • @mathsnerd22 you should await for `fetchData()` – Konrad Aug 15 '22 at 16:25
  • `async function fetchData() { const data = await fetch('//some url'); return await data.json(); } export const data = fetchData(); console.log(data) //returns promise` – mathsnerd22 Aug 15 '22 at 16:26
  • I checked on codesandbox and `'await' is only allowed within async functions` so it's not possible in browsers yer – Konrad Aug 15 '22 at 16:27
  • how can I go about this? i'm trying to store the data in a variable then export that variable across another reactjs page – mathsnerd22 Aug 15 '22 at 16:30
  • `await` for it in the other files for example – Konrad Aug 15 '22 at 16:31