Leveraging asynchronous response data within asynchronous components

Here's the structure of a parent component and a child component:

export default {
    name : 'parentNode',
    mounted: function () {
        var that = this;

        if (that.$store.state.auth.isAuthenticated) {
        
            that.$store.dispatch(ActionsType.GET_ALLCOINLIST).then(function (data) {
            // Utilizing store data in child components.
                that.$store.state.main.data = data;
            });
        }
    },
};

export default {
    name : 'childNode',
    data : function(){
        return {
            childData : {}
        }
    },
    mounted : function(){
        //How can I ensure the data is loaded before proceeding?
    },
    computed : {
        childData : function(){
            return this.$store.state.main.data;
        }
    },
    watch : {
        childData : function(){
            this.makeChart();
        }
    },
    methods : {
        makeChart : function(){
            console.log('Creating a new chart with the data.');
        }
    }
}

The goal is to update the chart whenever the $store(vuex) data changes. Due to the asynchronous nature of the data response, there is a challenge when the child component loads without the necessary data from the parent.

The ideal scenario is to always have the chart populated with the initially retrieved data when the child component first loads. Vue components load asynchronously, so how can we control this behavior? Currently, the chart might not be generated on initial load of the child component.

Answer №1

For managing state in Vue.js, you can utilize the mapState() and watch() methods:

import Vue from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="394f4c5c790b170f17080d">[email protected]</a>";
import * as vuex from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="710704140931425f475f43">[email protected]</a>";

Vue.use(vuex)

var store = new vuex.Store({
  state: {
    count: 1,
    isLoaded: false, // update when async call completes
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    init() {
      setInterval(() => this.commit('increment'), 1000) // replace with async call and update isLoaded after
    }
  }
});

var app = new Vue({
  el: '#app',
  store,
  data() {
    return {
    }
  }, computed: {
    ...vuex.mapState([
      'count'
    ]),
  },
    watch: {
      count() {
        console.log('watch count', this.count)
      }
    },
  mounted() {
    this.$store.dispatch('init')
  }
})

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

Attempting to delay iteration of NodeJS list until it has been fully populated

I have created a piece of code that uploads a file, runs it, and compares the output with expected results. Now, I want to enhance this functionality by running the uploaded file multiple times, each time comparing it against different expected outputs or ...

How can Ajax assist in utilizing a JavaScript variable within a Rails call that is made within a JavaScript function?

I'm facing a challenge where I need to update a Ruby on Rails partial within a view using a JavaScript object-defined variable, but I'm struggling to make it work. Despite my research pointing towards using an Ajax call as the only viable solutio ...

Creating a loading spinner in a Vue component while using the POST method

After successfully creating a loader for fetching data using the GET method, I encountered challenges when attempting to do the same with POST method. Is there a reliable way to implement a loader during the POST data process? For GET method, I set the lo ...

Error: The property "id" cannot be destructured from req.params because it is not defined

I am attempting to retrieve a user profile from a database and return it as a JSON object when the profile URL (localhost:3000/Profile/1) is accessed. However, I am encountering an error: TypeError: Cannot destructure property id of req.params as it is un ...

Ionic - Retrieve data from a Universal Resource Identifier

When using my application, users have the option to select and crop images using Ionic Native - Crop. Once they have cropped their image, I will receive the URI of the image, for example: file:///storage/emulated/0/Android/data/com.myApp/cache/15353694789 ...

What is the reason for the index.html file not connecting to the local .css files and .js file?

I'm currently using node.js to send an .html file that includes the following tags: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="description" content="This is my personal profile website" /> <link r ...

There was a problem encountered while running a GitHub code that was last updated on January 10, 2023

Recently, I embarked on the journey of creating my own private messenger using Flask. The Github code that caught my attention seemed promising. However, upon executing flask run as per the instructions in the provided "README.md" file on Ubuntu 22.04 comm ...

Unexpectedly, the child component within the modal in React Native has been resetting to its default state

In my setup, there is a parent component called LeagueSelect and a child component known as TeamSelect. LeagueSelect functions as a React Native modal that can be adjusted accordingly. An interesting observation I've made is that when I open the Lea ...

Exploring AngularJS Navigation in Windows 8 App Store Applications

Hello, I recently started learning about developing Windows Store apps. I found a way to incorporate AngularJS into my Windows 8 store app by making some adjustments in the AngularJS library. However, I'm now struggling with implementing AngularJS rou ...

The function to refresh content is causing errors in the code

Creating a comment and replies form where the replies display underneath each comment. I've encountered an issue where I can post replies normally, but when attempting to delete a reply, I must refresh the page. After refreshing, I'm only able to ...

Displaying Laravel data based on user-selected dropdown option

Struggling for an hour to dynamically change the value of an input field based on the product selected from a dropdown menu, but can't seem to solve it yet. This is how the products are populated: <select name="product_id" v-model="form.product_id ...

I encountered an error from DataTables when trying to set the width of the header cells using the original width of the columns

                 Help! I keep getting an error message: DataTable Uncaught TypeError: Cannot read property 'style' of undefined Does anyone have any ideas on how to fix this?   I keep seeing the following error message: Uncaught Typ ...

What is the best way to simulate an unexported function in Javascript jest environments?

Testing a module in my vuejs project is what I'm currently focusing on. import { getBaseUrl } from "@/application/api/baseUrl"; export default ( uri: string, requestBody: Record<string, string | number> ): void => { let form ...

The chosen value remains constant even after altering the selected option

I am trying to create a scroll-down bar that allows users to select different options, and once an option is selected, its value should appear in the bar. However, I'm facing an issue where the value does not change according to the selection: const [ ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

disabling past dates in Bootstrap calendar

How can I disable past dates in Bootstrap easily? <script type="text/javascript"> $(function(){ $('.datepicker').datepicker(); }); </script> Date: <input type="text" class="datepicker"></input> I have added the ...

Does JavaScript adhere to a particular pattern?

Is there a more streamlined approach to implementing this particular design pattern? function a() { function x() { /* code */ } function y() { /* code */ } /* additional code */ x(); y(); // can be called from here } a(); a.x(); a.y(); I ...

The server nodejs is unable to recognize the dotenv file

This is my very first project with the MERN stack and I'm currently working on pushing it to GitHub. Since I am using Mongoose, I needed to protect the login credentials for my account. After some research, I discovered the solution of using a .env fi ...

There appears to be an issue with the server, as it is reporting a TypeError with the _nextProps.children property not

As a newcomer to coding, this is my first question on the forum. I appreciate your understanding and patience as I navigate through some challenges. I'm currently working on making my NextJS SSR app responsive, but after modifying the index.js and ot ...

Anomaly in Date String Comparison within Angular Controller

Having a puzzling issue when attempting to compare two date strings within my Angular Controller. It seems that the comparison is yielding unexpected results. To explain, I first convert today's date to a string ("2/5/2016") and then proceed to use it ...