-1

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?

Phat Baba
  • 53
  • 7

1 Answers1

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.

David
  • 208,112
  • 36
  • 198
  • 279