Issue arises with asynchronous function outside of mounted lifecycle hook in VueJS

Identifying the Issue

I encountered an issue while trying to create an external async function and assign its return value directly to a state variable. In addition, I passed firebase reference and store to this function to avoid importing them again in the JavaScript file. Another requirement was to set the state.isLoading to false only after the completion of the async function. However, when I checked the console, it showed:

Promise { "pending" } ​ : "fulfilled" ​ : Array [ {…} ]

This indicates that my array is present, but I am unsure how to access its values.

Thank you for your assistance!

Vue Code

import {CreateUserFoldersList} from "@/path";
import {useStore} from 'vuex'
import {onMounted, reactive} from "vue";
import {useRouter} from 'vue-router'
import fire from "@/utilities/fire";

export default {
  name: "FlashcardsBrowser",
  setup() {
  • I want to assign the returned value from the function to a variable in the state object
    onMounted(() => {
      state.Folders = CreateUserFoldersList(store.state.UserData.AuthUser.uid, fire)
      state.isLoading = false
    })

    const router = useRouter()
    const store = useStore()


    const state = reactive({
      Folders: [],
      isLoading: true,
      isShowingModal: false,
    })
    return {
      state
    }

External Function

export async function CreateUserFoldersList(storeUserData, firebaseRef) {
    let mainFolder;
    await firebaseRef.database().ref(`UserData/${storeUserData}/Folders`).once('value').then((snapshot) => {
         const data = snapshot.val()

         let Folders = []
         if (data) {
             Object.keys(data).forEach(key => {
                 Folders.push({
                     id: key,
                     name: data[key].name,
                     length: data[key].length
                 })
             })
         }
        mainFolder = Folders
     })
    return mainFolder
}

Your help would be greatly appreciated, thank you!

Answer №1

Give the function a try using await:

 onMounted(async () => {
    state.Folders = await CreateUserFoldersList(store.state.UserData.AuthUser.uid, fire)
    state.isLoading = false
 })

Answer №2

state.Folders = await CreateListOfUserFolders(store.state.UserData.AuthUser.uid, fire)

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

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

Using the fetch method to consume a RapidAPI JSON response

Currently, I am in the process of learning React Native and have initiated a project for that purpose. In this project, I have integrated RapidAPI (link: ) to fetch necessary data. Upon hitting the API, I receive a 200OK status, but unfortunately, I am fa ...

Selenium and AngularJS patiently wait before carrying out specific actions

I have been using selenium to test an AngularJS application and I am encountering an issue where I am unable to perform any actions on the page until it is fully loaded. Although I have considered using Thread.sleep(), I am aware that this is not the most ...

Access an attribute using slashes in Jquery

I've been struggling to use jQuery to select an object based on a unique filename attribute. However, I'm facing issues with escaping slashes when the selector is created using a variable. Despite spending hours trying different combinations, I s ...

Why are my pages not refreshing when the URL changes with hash history?

Experiencing an issue with Vue + NUXT while in hash mode, yet no issues in regular history mode. After changing the URL from /#/test/1 to /#/test/2, the $router updates correctly, but reactivity is not triggered. How can I properly trigger reactivity when ...

What are the steps to fix a timeout error with React.js and socket.io acknowledgements?

My setup includes a Node.js server and a React.js client application. Data is exchanged between them using socket.io, but I'm running into an issue with implementing acknowledgment. Whenever I try to implement acknowledgment, I receive a timeout error ...

Is there a way to combine Vue3, Stripe, and Typescript for seamless integration?

I am currently developing a Vue3 application and running into some issues while trying to integrate Stripe. I am facing difficulty in incorporating it successfully. Here is the code snippet from my Vue3 component named Checkout.vue: <template> .... ...

Creating a custom type for accepted arguments in a Typescript method

Below is the structure of a method I have: const a = function (...args: any[]) { console.log(args); } In this function, the type of args is any[]. I am looking to create a specific type for the array of arguments accepted by this method in Typescript. ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Unable to retrieve scripts upon returning to the main page of a Jquery website

Starting fresh with this post, I'm feeling incredibly frustrated and close to giving up on JQM completely. This shouldn't be so difficult. Here's my website structure: OUI/ index.php js/ pages/ images/ On the index.php page at http://loca ...

Storing a selected database column as a variable from an HTML page in Node.js with Express

My website showcases flight information pulled from a MySQL database. The process begins with a form where users select destinations and dates for their desired flight. Once the form is submitted, users are directed to another page where flights matching t ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...

What could be causing me to see a basic checkbox instead of a toggle switch in my React application?

I've been attempting to create a toggle switch that activates dark mode using Bootstrap switches, but when I save the code, it reverts back to a basic checkbox. According to the documentation, for older assistive technologies, these switch elements wi ...

What is the process of implementing a page change using a GET request in JavaScript using Node.js and Express?

Within this application, users are provided with a table where they can input data. Each row in the table is equipped with an "Edit" button that, when clicked, should redirect them to a new page labeled "/update" where modifications to the specific row can ...

Error: Laravel API request unsuccessful

After seeking advice in larachat and conducting thorough research on Google, I discovered that while similar inquiries have been made in the past, none of the suggested solutions seem to work for my particular case. My current challenge involves loading c ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

Simple steps to convert Redux state to Redux Persist with the help of 'combineReducers' function

I'm facing a challenge trying to implement Redux-Persist with my Redux state, particularly because I am using combineReducers. Here is the structure of my store: import { createStore, combineReducers } from 'redux' import { usersReducer } fr ...

Having trouble extracting the Top-Level Domain from a URL

I'm struggling to find a reliable way to extract the Top-Level Domain from a URL. The challenge I'm facing is that the URLs entered by users can vary greatly - they might enter www.google.com, m.google.com, m.google.uk, google.uk, or www.m.google ...

CSS responsive design: concealing elements does not prevent the page from being displayed

Imagine a scenario where I need to display a template in two different versions based on the user's device. For instance, I have utilized the following code: <div class="desktop"> <body> Hi Desktop user </body> </div> ...