Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Use fetched API data outside of the function

To make my code cleaner I want to use fetched API data in a few different functions, instead of one big. Even though I 've did manage to reffer to that data in other functions, the problem is the API im a fetching throws different, randomized results every time it is called. And so the output from userData() does not equal that from userData2(), even though my intention is different and I'd like the result variable contents to be the same between functions.

const getData = () =>
  fetch("https://opentdb.com/api.php?amount=10").then((response) =>
    response.json()
  );

const useData = async () => {
  const result = await getData();
  console.log(result);
};

const useData2 = async () => {
  const result = await getData();
  console.log(result);
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your getData() function returns a promise. One fun fact about promises is that while they can only resolve once, that resolved value can be accessed and used as many times as you want.

const dataPromise = getData();

const useData = async () => {
  const result = await dataPromise;
  console.log(result);
};

const useData2 = async () => {
  const result = await dataPromise;
  console.log(result);
};

Using await resolves the promise value, the equivalent of...

dataPromise.then((result) => {
  console.log(result);
});
// or `dataPromise.then(console.log)` if you like brevity

I like to point this out about the fetch-api... you should always check the Response.ok property

const getData = async () => {
  const res = await fetch("https://opentdb.com/api.php?amount=10");
  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`);
  }
  return res.json();
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!