How to export fetch resuts to other module

Hi!

I need to get userId from a server and later use it in a variety of functions, which manipulate content with some conditions based on that id.

I do so with this function:

let user = {};

export async function getId() {
  const response = await fetch(
    "https://nomoreparties.co/v1/" + `${cohortId}` + "/users/me",
    {
      method: "GET",
      headers: apiConfig.headers,
    }
  );
  let data = await response.json();
  data = JSON.stringify(data);
  data = JSON.parse(data);

  return data._id;
}

user.id = await getId();

const userId = user.id;

But I also need to export resulting variable (user.id) to other js modules, but there it arrives as undefined, because the variable is copied before the fetch returns the value from the server.

How do I do that?

What I’ve tried:

  • exporting it as an object (which is not a copy, but a reference to original values, but it is still undefined)
  • exporting the function stated above and trying to call it the desired module, which results in some kind of defense protocol being triggered:

Stuck on this for some time already, please help.

I don’t see an export for user.id anywhere.

Examples: https://replit.com/@lasjorg/ImportExport-fetch-data


As an aside, why you are doing stringify/parse?

The error is stating that api.headers is undefined

also another side issue: you seem to be using an old old version of something, because async has been supported for quite a while now but whatever WebPack is running is converting the async code to generators (possibly you’re using Babel with the regenerator runtime?)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.