What is the best way to handle waiting for an API call in JavaScript export?

In my Vue app, I've set up my firestore app initialization code as shown below:

if (firebase.apps.length) {
  firebase.app()
} else {
  firebase.initializeApp(config)
}
export const Firestore = firebase.firestore()
export const Auth = firebase.auth()

Now, I want to fetch the config file from an API. Instead of directly calling `firebase.initializeApp(config)`, I aim to do something like this:

axios.get('https://.../config.json', {})
    .then(async ({ data }) => {
      firebase.initializeApp(data)
    })
    .catch((err) => {
      console.log('error', err)
    })

However, I need to ensure that my exports wait until I receive the response from the API and initialize the app.

Is there a way to achieve this by using async/await or any other pattern?

Answer №1

If you want to set up Firebase, you can follow these steps:

export const initialize = () => {
 try {
   return axios.get('https://.../config.json', {})
    } catch(err) {
      console.log('error', err)
    }
  }

In another JavaScript file, you can import the above code and then proceed as follows:

initialize().then(data => {
firebase.initializeApp(data)
firebase.firestore()
}).catch((err) => {
    console.log(err);
});

Remember, there is no need to export firebase.firestore() separately because it will be used in every JavaScript file if Firestore is required.

The essential method to export is firebase.initializeApp(data). You can include this inside the initialize() method and return it for convenience.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body. The structure of my database is as follows: "cart": { "items": { "0": {info here}, "1": {info ...

Leveraging the arguments object within function declarations

Could someone explain why the foo function functions properly? function foo (x,y) { return arguments.length; } However, when I call the boo function with arguments, it returns an error saying undefined is not a function. function boo (c,d) { return ...

Why is applying CSS on an li element using .css() in JQuery not functioning?

Hey there! Could you please review my code? I'm attempting to add a top position to the <li> element using a variable in jQuery, but I'm not sure how to do it. Here's the code: <script> $(document).ready(function(){ ...

Prevent global CSS from affecting VueJS by enabling only scoped CSS within components

Is there a way to eliminate all global CSS within a VueJS component and only allow scoped CSS? If so, how can this be achieved? Below is the issue I am trying to address: * { /* Global styles */ } /* Component-specific styles */ .items ul { } .i ...

Is there a way for me to retrieve the name of a newly opened browser tab from the original tab?

I have written a code snippet to create a new tab within the same browser by clicking on a link. function newTab() { var form1 = document.createElement("form"); form1.id = "newTab1" form1.method = "GET"; form1.action = "domainname"; //My ...

How can you refresh the source element?

Is there a way to make the browser reload a single element on the page (such as 'src' or 'div')? I have tried using this code: $("div#imgAppendHere").html("<img id=\"img\" src=\"/photos/" + recipe.id + ".png\" he ...

Issue encountered: Request for the key to be assigned to the <template> tag

After encountering an error for not including :key="item.id" on the <template> element, I added it as shown below: However, doing so resulted in a different error: Below is the code snippet causing the issue: <template v-for ...

convert and transform XML data into JSON format

I have been working with nodejs-expressjs and I received a response in raw XML format. My goal is to convert this raw XML into either a JavaScript array or a JSON array so that I can extract the domain name along with its status. I want to display this inf ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

Utilizing Pagination in Elasticsearch with MongoDB and ExpressJS

Despite my efforts to find a solution online, I have not yet come across anything that helps me achieve what I need. This is my first time working with ElasticSearch, and I am relatively new to Node.js and MongoDB as well. Following a tutorial, I impleme ...

Setting up ckeditor5 in Nuxt the right way

Recently, I encountered the CkEditor5 setting in Nuxt js for the first time and found it to be quite confusing with plenty of errors surfacing. I attempted to customize my version of ckeditor5 in nuxt.js by following this guide However, none of it seems ...

Cannot extract the 'name' property from 'e.target' because it is not defined

I encountered an error message stating that I cannot destructure the property 'name' of 'e.target' because it is undefined within the createform() method. Despite highlighting the line causing the error, I am still unable to comprehend ...

Using AngularJS to create a form and showcase JSON information

My code is below: PizzaStore.html: <!DOCTYPE html> <html ng-app="PizzaApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Delicious pizza for all!</title> ...

JS filter function is not functioning as expected. It's unclear what the issue might be

Check out my previous inquiry What could be the issue with my filter? I've implemented a filter, but it seems to have some glitches when dealing with specific values. The 'No Record Found' message doesn't appear as expected in certain ...

Having trouble with Material-UI Textfield losing focus after re-rendering? Need a solution?

I am currently utilizing Material-ui Textfield to display a repeatable array object: const [sections, setSections] = useState([ { Title: "Introduction", Text: "" }, { Title: "Relationship", ...

Update AngularJS data models using the callback function "on change" from a jQuery plugin

Currently, I am in the process of developing a web application for a touchscreen computer that requires an on-screen keyboard. After searching extensively, I came across this fantastic (or at least the best one I could find) keyboard plugin: https://github ...

Tally up various figures in all tables

I am dealing with a dynamic table generated from a PHP loop. Below is an example of the table structure extracted from the browser source code: <table class="table"> ... (table content) </table> <table class="table"> ... (t ...

Having trouble getting the jquery tabify plugin to work properly

I've put in a lot of effort and double-checked everything, but for some reason this tabify function just won't work. I have gone through my code 100 times but still can't seem to pinpoint the error. Here is the code I am working with: <! ...