Using Typescript with Vue to create a reactive exported variable

Scenerio Setup

Currently, I have developed a Vue3 + Firebase project which includes an object called userInfo in the main.ts file. The export declaration is as follows:

export var userInfo :any = {}

It is important to note that the :any declaration is utilized to address Typescript error

*some-property* does note exist on type Object
.

Furthermore, a hook inside the main.ts file sets this object when a user is authenticated, as demonstrated by the code snippet below:

auth.onAuthStateChanged(async () => {
    if(!auth.currentUser) return

    userInfo = await getUserInfo()
})

However, it's worth mentioning that the object is only populated once the onAuthStateChanged hook is triggered, which occurs after imports are processed in the .vue files.

Identified Issue

The challenge arises when attempting to import the ´userInfo´ object in a .vue file using import {userInfo} from '@/main'. In this scenario, the file imports the empty object prior to the hook filling the object with data.

Consequently, even after the onAuthStateChanged hook completes and populates the object, the component does not automatically refresh the import, resulting in the absence of required data within the .vue file.

Key Inquiry

My desired approach involves centralizing the acquisition of the userInfo object, allowing me to simply import it into my .vue components rather than manually retrieving it each time it's needed.

How can I navigate through this challenge where the object is filled after imports have been processed?

Answer №1

It has been widely recommended to utilize a store for your project, especially when working with Vue3 and Typescript. A great option is Pinia, which is the most current and updated store manager for modern Vue applications, as opposed to the older VueX.

You can find helpful examples in the documentation. I personally implemented Pinia in a similar way for a personal project, which may provide some assistance for your project as well.

Answer №2

If you want to enable communication between child components and parent components in Vue, you can achieve this by creating a mutation using Vuex. This allows for interaction from anywhere within the application. For more information and an example, you can refer to this tutorial:

Additionally, you can use the following code snippet to asynchronously get the authenticated user ID:

export async function getAuthUserID(): Promise<string | undefined> {
  return await new Promise( (resolve, reject) => {
    firebase.auth().onIdTokenChanged(async (user) => {
      if (!user) {
        resolve(undefined);
      } else {
        resolve(user.uid);
      }
})
  }).then((uid: string | undefined)=>uid).catch(function(e) {
    throw (e);
  });
}

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

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

What is the best way to implement an Angular application within the child routes of another Angular application?

Is it possible to load an Angular app using lazy-loading (when a specific route is hit by users) into another Angular app without compiling the first one for use in the second? This is the Routing-Module of the app to nest into an Angular app: const upgr ...

Despite returning an "OK" status, the jQuery Ajax Codebehind Post fails to function properly

Attempting to call a function in ASP.NET with jQuery Ajax: var params = "{'name':" + "\"" + name + "\"}"; $.ajax({ type: "POST", url: "CreateTopic.aspx/CreateNewTopic", data: params, ...

Converting PHP code to utilize AJAX in JS

Within the confines of a single file (invasions.php), I have the following code: <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='con ...

When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I' ...

How can we rearrange the newly added row from onRowAdd in Material Table to be displayed at the beginning of the section?

Title. According to the documentation for material table, when using editable with onRowAdd, the new row is always added at the bottom of the section. Is there a way to have it appear at the top instead? Alternatively, how can I add an onClick effect so t ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

Adjusting the size of an HTML5 canvas using a class function when a resize event occurs

I'm attempting to adjust the size of a canvas element using a resizeCanvas() method triggered by a resize event. When I directly call the method, the canvas resizes without any issues. However, when the event handler triggers subsequent calls, I encou ...

Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file. Although I ha ...

Steps to automatically set the database value as the default option in a dropdown menu

I'm in need of assistance with a project that I'm working on. To be completely honest, I am struggling to complete it without some help. Since I am new to Angular and Springboot with only basic knowledge, I have hit a roadblock and can't mak ...

Understanding how objects are created using the reduce method

I'm curious about how the reduce function can transform an array into an object as shown in this example, particularly with the line: p[c[0]] = c[1]; Is this an unconventional syntax for creating key-value pairs that I haven't encountered before ...

ReactJS - Element not specified

I'm experiencing a specific issue with the component below related to the changeColor() function, which is triggering an error message: TypeError: Cannot set property 'color' of undefined This error seems to be isolated within this compo ...

Rendering a Nativescript component once the page has been fully loaded

I'm currently working on integrating the WikitudeArchitectView into my TypeScript code. I've successfully registered the element in the main.ts TypeScript file: var architectView = require("nativescript-wikitudearchitectview"); registerElement ...

Display the Sencha Touch Picker with the previously selected option showing

When using the Sencha Touch Picker component, I noticed that if I select a data and then hide the picker, upon showing it again, only the first record is selected each time. I want the picker to display my last selection when shown again. To achieve this ...

Vue js throws a maximum call stack error when updating a Chart component

I have successfully created a line chart using the Chart.js 3.5 library. The chart is responsive, all animations are working fine too. I am currently facing an issue where I am attempting to update the data from a parent component and trigger a chart updat ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

changing a variable in javascript

Is there a way to successfully update the "storage" variable set in uploadify? I have a function called set_path that is designed to modify the variable by combining it with other values whenever specific content is selected. $(document).ready(function () ...

What is the best method to determine when 20% of a "<section>" element is within the user's view?

Looking at the layout, I have two sections that take up the entire page. My goal is to detect when the second section is 20% visible while scrolling, and then smoothly scroll to lock that section in place so it occupies the full space. This action should a ...

The API request is experiencing delays due to the large dataset of 250,000 records

Utilizing API calls to retrieve data for the frontend is essential, but with a database table containing 250,000 rows, efficiency becomes a concern. In my .NET Core application, I implement the following query: IQueryable<Message> query = context.Me ...

Having trouble getting the group hover animation to function properly in Tailwind CSS

Just starting out with tailwind css and running into a little issue. The hover animation I'm trying to apply isn't working as expected in this case. Instead of seeing the desired animated background when hovering over the group, it seems the back ...