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

Tips for navigating libraries with Google CAJA

Is there a way to configure Google Caja to allow specific libraries to work without being sanitized? I have my own CAJA server and an application based on NodeJS. I'm providing users with code that is mostly related to charts and graphs, but certain ...

Tips for sending a set to a directive in angular.js?

Forgive me for my confusion. I am passing the name of a collection to my directive: <ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul> This is how the directive is defined: a ...

Hold off on moving forward until the content has been loaded using ajax within loops

I am facing an issue with waiting for ajax requests to complete before proceeding. My task involves iterating through all the options in five select lists. Upon selecting an option in "Select1", it dynamically loads or refreshes "Select2". The same proces ...

"Trouble connecting Sequelize associations with API routes, resulting in unsuccessful retrieval of data from the database

I am currently navigating the complexities of sequelize and express, facing challenges with database associations and data retrieval. My project involves a boarders-boards (focused on surfboards and riders) database with three main models: Boards, Riders, ...

ng-click="showInventory()" onClick="currentTemplate='/inventory.html'" Not

I'm facing an issue with my menu list. When I apply the ng-repeat directive, it seems to not work properly. However, when I remove the ng-repeat, everything functions as expected. <div class="reports_header_tabs_holder"> <span ng-repea ...

Creating an array of options for a jQuery plugin by parsing and populating

I am currently in the process of developing my very first jQuery plugin. The main function of this plugin involves taking JSON data and loading it into a table. Although most of the logic has been implemented successfully, I am facing challenges when it co ...

Issue arising from the lack of direct communication between parent and child elements

I am facing an issue with indirect communication in a react native application. The situation involves a parent component, implemented as a class component, and a child component, which is a functional component. Here is the Parent component: constructor ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

Encountering a 404 error in an AngularJS app within Cordova on Android

Currently, I am working on an android application using Cordova and AngularJS (front-end framework OnsenUI). Below is the code snippet for my GET request to retrieve data from the server: $http.get(url+"getlotterylist").then(function(msg){ $scope. ...

What could be the reason my vue.js button is not generating a fresh textarea?

I am currently developing my first Web App with vue.js and I'm trying to implement a feature where clicking a button will generate a new textarea. It seemed to be functioning correctly when tested on jsfiddle, but once I tried running it in visual stu ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...

Using ES6, when utilizing array map in ReactJS, the function does not produce a return value

One challenge I'm facing involves mapping an array to find a specific string value. Unfortunately, despite my efforts, the map function is not returning anything as expected. class Application extends React.Component { constructor(){ super(); ...

An unexpected error occurred while attempting to retrieve data from Firebase and display it in another component

An error occurred: Unhandled Runtime Error Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components) but got undefined. This could be due to forgetting to export your component from the defi ...

Can Vue recognize array changes using the Spread syntax?

According to Vue documentation: Vue is unable to detect certain changes made to an array, such as: Directly setting an item using the index, for example vm.items[indexOfItem] = newValue Modifying the length of the array, like vm.items.length = newLength ...

Your search parameter is not formatted correctly

I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example: http://localhost:3000/patient?filter=name:jack I have implemented a method to retrieve and convert these ...

Enhancing speed on an extensive list without a set height/eliminating the need for virtualization

My webapp includes a feature that showcases exhibitors at an expo. The user can click on "Exhibitors" in the navigation bar to access a page displaying all the exhibitors. Each exhibitor may have different details, some of which may or may not contain data ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Tips for displaying the message "{"POWER":"ON"}" within the else if statement (this.responseText == ({"POWER":"ON"})) {

Hey everyone, I'm trying to adjust the color of a button on my webpage based on the response I receive from this.responseText. I understand the JSON response, but for some reason, I can't seem to incorporate it into my code. If anyone could lend ...

Caution: The file path in node_modules/ngx-translate-multi-http-loader/dist/multi-http-loader.js relies on the 'deepmerge' dependency

My micro-frontend angular project is using mfe (module federation). I recently updated it from angular 13 to 14 and encountered some warnings such as: node_modules\ngx-translate-multi-http-loader\dist\multi-http-loader.js depends on ' ...

Conceal the parent div from its sibling within the same parent container

My goal is to conceal a parent component from its child element. I attempted to achieve this by using the parent component as a background while adding additional backgrounds to the child elements for overriding purposes. However, this method did not work ...