How can I export a variable after initializing once?

Viewed 426

I have an api call setup to retrieve some data I need when my express server starts and I want to reuse this data across multiple files by importing it. Basically making it a global, but only accessible via import/export.

UPDATE: I ONLY want to make the getCreds api call ONE time, since they will not change and then reference the creds throughout my app.

I'm not sure the best way to accomplish though. :/

file1.js, file2.js, etc...

import creds from './libs/creds.js'

...use creds for something...

libs/creds.js

// not sure how to set creds once and export it

let creds;

const getCreds = async () => {
  ...api call to get creds, but do not want to call repeatedly...
  creds = api.data
}

export { creds };
3 Answers

I dont know if there are any better ways, but what i do is export a getter function instead:

let _creds;

const getCreds = async () => {
  ...api call to get creds, but do not want to call repeatedly...
  _creds = api.data
}

function creds() {
    return _creds;
}

export { creds };

This way every time you call creds() you get the updated value of _creds

You could even put the API call in the creds getter function and then cache it like so:

let _creds;

export function credsGetter() {
    if (_creds) {
       return _creds;
    } else {
        ...do the API call
        _creds = response.data
        return response.data;
    }
}

Then you can import it like this:

import { credsGetter } from "someFile";

const creds = credsGetter();

You dont need to worry about the API getting called multiple times, because it caches the value : )

Anyways I dont know if there is a better solution to this, ive been looking for it too but this is the only working thing i couldve come up with.

I would try doing it like this

let creds;

const getCreds = () => {
  ...api call to get creds, but do not want to call repeatedly...
  creds = api.data
}

getCreds();

export { creds };

Import it anywhere, and it should be called once.

How about you make this a middleware and make the call once your app starts and store the data in your response.locals where you can access it anything you need it.

Related