Exploring Vue 3's composition API and its impact on managing undefined variables within the

As a newcomer to Vue.js, I encountered an issue while working on my initial project that seems to be related to the component's lifecycle.

Here is the scenario: I am using Vue 3 with the composition API.

Within my "Map" component, I utilize d3.js to display a chart. In my Setup() method, I have both onBeforeMount() and onMounted() functions. In onBeforeMount(), I attempt to fetch data from my Firestore database for the chart values. The data appears correctly when logged on line 47. However, in onMounted(), where I intend to create my d3 chart, I find that the data is undefined when accessed (as seen on line 55)...

My goal is to retrieve data from the database within the "Map" component to generate the chart, allowing another component called 'MapSettings' to modify the data or filters and automatically update the chart accordingly. Both components will share the same parent component, positioning "Map" and "MapSettings" as siblings within the hierarchy.

But before proceeding further, understanding why the data is coming back as undefined is crucial. Any assistance or suggestions would be highly appreciated!

https://i.stack.imgur.com/u4Zwt.png

https://i.stack.imgur.com/nu0YI.png

Answer №1

Your lifecycle hooks are well-written. The issue you're encountering is related to the execution of asynchronous and synchronous code.

You have a function that utilizes the async-await feature, which means it will run asynchronously. In this scenario, you're fetching data from Firestore and storing it in a reference during onBeforeMount().

Conversely, you have a standard function within onMounted() where you attempt to access the value of the reference. However, because the function defined in onBeforeMount() has not completed its execution (or is still in the event queue) when onMounted is triggered, you end up with a result of undefined.

This explains why you initially see the console.log output from onMounted.

A possible solution is to combine both functions into one lifecycle hook and utilize async await:

setup() {
  const {actorDocs, load} = getActorDocs()
  const actorsData = red([])

  // load actor data from db
  onBeforeMount( async () => {
    await load()
    actorsData.value = actorDocs
    console.log(actorsData.value)
    // manipulate data here...
  })
}

It's important to note that you cannot "pause" a lifecycle hook with async-await. What actually pauses is the function that Vue plans to execute within that hook. This distinction is crucial as pausing an entire hook would not be efficient.

Answer №2

Dealing with a similar issue, I am trying to access imgsRef.value outside of the onBeforeMount scope. How can I retrieve imgsRef value from outside of the beforeMount scope?

onBeforeMount( async () => {
  await axios
  .get("http://localhost:3000/ourMoment")
  .then((response) => {
    imgsRef.value = response.data
    
    // imgsRef gets the value from the API
    console.log(imgsRef.value.photo)
  })
})

// Even when I try to log here, the value remains empty
console.log(imgsRef.value)

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

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...

Display a Vue.js div element based on conditions matching a specific variable value

Is it possible for Vue.js to display a div only when a defined variable is set to a specific value? Currently, v-show="variable" can be used to show the div if the variable is set. However, I would like to know if v-show="variable=5" can be implemented t ...

What is the reason for the sharing of component data between two separate components using vue-apollo?

Currently, I am engaged in a fresh project utilizing vue along with vue-apollo. There is one component dedicated to displaying the user's name (UserShow.vue): <template> <div v-if="!this.$apollo.queries.user.loading"> Your na ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Tips for resolving the "semicolon expected" alerts in your CSS code (css-semicolonexpected)

Having some trouble with using the Tailwindcss @apply directive within a <style> tag in a Nuxt.js Vue file. It seems to be working fine, but those annoying red squiggly lines keep popping up. Any help would be greatly appreciated! Thank you! Take a ...

The issue with combining Laravel 5.4 event broadcasting and Vue.js has been a challenging obstacle to

Looking to set up a chat system using Laravel 5.4, Vue.js, and Pusher API with Echo. I have tried twice to establish communication with Pusher, but I haven't received any callbacks in my Vue component. I am working locally with MAPM. I have installed ...

How can you identify when a Vuetify radio button is re-selected?

Currently, I am developing a wizard that involves triggering navigation when a radio button is selected. Users should also be able to go back and change their previous choices. However, one issue I have encountered is the difficulty in detecting a re-selec ...

Experience a clean slate with Vue.js 3 after running 'vue serve'

Hey there, I'm having trouble figuring out what's going on. I've tried using two different libraries with no success. I have VueJS 3 installed through Vue Client and it worked fine initially. But when I tried creating a view or component to ...

NavigAuth - NativeScript Vue's Innovative Authentication-driven Navigation

After spending hours trying to figure this out, I need to ask for help. How can I create a simple Auth-based Navigation within my App? I have successfully set up a Firebase auth user inside my Vuex using an auth listener. Now, all I want is to display th ...

Utilizing the Power of GrapesJs in Vue3

Recently, I attempted to integrate the GrapesJS editor into my Vue.js project, but encountered some difficulties. The editor was not visible in the browser, and the designated tag for the editor appeared empty. Here is my editor configuration: <template ...

Incorporating Vue Component According to URL Parameters Dynamically

Is there a way to dynamically import a vue component based on a path provided in the URL parameters? For example, if <host>/<path> is entered into the browser, I would like to load a vue component located at <path>.vue. In my routes.js f ...

When using @mouseover, it is not possible to modify a variable's value

The hover event is not functioning properly in this Vue component. Although I was able to call a function on hover successfully, I encountered issues when trying to change the hover variable directly. <template> <div @mouseover="hover = t ...

Is there a way for me to adjust the font size across the entire page?

Most CSS classes come with a fixed font-size value already set. For instance: font-size: 16px font-size: 14px etc. Is there a way to increase the font size of the entire page by 110%? For example, font-size: 16px -> 17.6 font-size: 14px -> 15.4 ...

When attempting to add validation to the datepicker component in Vue.js, the default behavior displays an error message automatically

//I have integrated a datepicker component into my HTML code and I would like to add validation that shows an error message when the user moves away from this field and onto another input field in the form <datepicker v-model="present_complaint.experie ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

What is the most efficient way to transfer data from PHP Laravel to Vue.js and automatically update a Vue.js component whenever the data is modified?

New to Vue.js and feeling a bit lost about how reactivity works with it. I want to send data from PHP Laravel to a Vue.js component and have the component update automatically when the data changes. I've come across suggestions on Stack Overflow reco ...

Exploring methods to iterate through information in a Java enumeration and display it within a VueJS component

Is it possible to display report data stored in a Java enum using Vue CLI? enumExample.java public enum DefaultFormatE { Report001 ("Report001", "HTML", "ReportName001"), Report002 ("Report002", "PDF", "ReportName002"), Report ...

How can I modify the query parameter value in vue-router?

router.push({ path: 'register', query: { plan: 'private' } }) will create a URI like: http://localhost:3000/#/register?plan=private&plan=public in case the query parameter with key plan and value public already exists in $currentR ...

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...