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

143
Views
Is there a way to store async get call in a variable

I have a js file that is used in a React component. What I am trying to do is to fetch data from my endpoint and pass it to a variable called employees. I've tried different ways to do it, read about async and etc and I couldn't figure out how to do it, here is my attempt:

async function fetchData() {
    const response = await fetch('https://mocki.io/v1/29b83c0b-1a55-430d-a173-92b3632e04aa');
    const data = await response.json();
      return data
}


  export const employees =  fetchData() 

How can I pass my data to the employees variable?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You're essentially thinking about this the wrong way. Particularly in this statement:

How can I pass my data to the employees variable?

The variable is immaterial. What you're exporting is the value referenced by the variable. In this case that value is a Promise, and anything importing it would need to await that Promise.

But in the case of exporting modules like this, that structure is unintuitive and can lead to bugs. The module should just be exporting the functionality and the consuming code can invoke that functionality when and where it chooses to.

So don't invoke the function and export the promise. Export the function:

export async function fetchData() {
  const response = await fetch('https://mocki.io/v1/29b83c0b-1a55-430d-a173-92b3632e04aa');
  const data = await response.json();
  return data
}

(Though I'd personally recommend giving it a better name than fetchData. Something like fetchEmployees seems more descriptive, given the variable employees in the code shown.)

Then consuming code would import that function and use it to get the data:

import { fetchData } from 'your-module';

// sometime later, either this:
const employees = await fetchData();
// do something with employees

// or this:
fetchData().then(employees => {
  // do something with employees
});

This keeps the module responsible for just one thing, providing consuming code with the functionality it needs. The module shouldn't also be responsible for invoking that functionality, and trying to do so will cause problems when that functionality is asynchronous in nature.

about 4 years ago · Santiago Trujillo 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!