Tips for updating child components with the most recent parent data following a page refresh

Currently, I am in the midst of a project where I am utilizing Vue.js for the frontend development. Below is the snippet of code from the main.js file:

new Vue({ // eslint-disable-line no-new
      //el: '#app',
router,
 data () {
  return {
      friends: []
  }
},
methods: {
    getFriends: function () {
        return this.friends;
    }
},
created: function () {
    this.$http.get('/user/' + this.getUserIDCookie('userID')
        + '/friends').then(function (response) {
        this.friends = response.data;
    });
},
components: {
    'nav-bar': require('./components/Navigation.vue')
},
template: `
    <div id="app">
        <nav-bar></nav-bar>
        <router-view class="router-view"></router-view>
    </div>`
}).$mount('#app');

In a specific page scenario(for instance, when redirected to localhost/#/user/1/details), I'm trying to fetch the list of friends from main.js as shown below:

<script type="text/babel">
export default {
    name: 'profile',
    data: function () {
        return {
            user: {},
            friends: []
        }
    },
    methods: {
        // Some methods
    },
    created: function () {
        this.friends = this.$root.getFriends();
    }
}
</script>

An issue arises when I refresh the current page. Following the refresh, this.friends ends up being null or undefined as this.$root.getFriends() returns null/undefined. While I can relocate it to the user component, my preference is to retain it in main.js so that the GET call is executed once and the data remains accessible throughout the application.

If you have any suggestions on how to address this complication, please do share your insights. The version of Vue being used is 2.0.1

Answer №1

To ensure the component has access to necessary data, it is recommended to pass them as props.

One simple way to achieve this is by using the following method:

<router-view class="router-view" :friends="friends"></router-view>

In the profile component, implement the following code:

export default {
    props:["friends"],
    name: 'profile',
    data: function () {
        return {
            user: {},
            friends: []
        }
    },
    methods: {
        // Include necessary methods here
    }
}

If you are looking for more advanced options, newer VueRouter versions offer various ways to pass properties to routes.

Additionally, consider utilizing Vuex or other state management tools if your application becomes more complex.

Answer №2

The issue arises when the page is refreshed, causing the entire application to reload, including the get function, which operates asynchronously. As the router determines the need to render the details component, it begins loading that component and calls the getFriends function, but the asynchronous get call has not yet concluded.

One possible solution would involve storing and retrieving the Promise from the get function; however, as Bert mentioned, the preferred Vue approach is to pass data as props rather than having child components fetch it from parent components.

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

"Utilize the canvas to crop and draw an image

Hello, I have an image with a size of 750x554. To load the image into an img tag, I use the following method: <input type="file" accept="image/*" onchange="document.getElementById('character').src = window.URL.createObjectURL(this.fi ...

What makes websockets too complex for basic applications?

Source: It is mentioned that a WebSocket connection is designed to be persistent, which could be unnecessary for simpler applications. For example, when referring to socket.io, which acts as a wrapper around websockets and simplifies the setup process, ...

Learn how to pass the rel attribute value from a clicked image to a method using Vue.js

I'm currently delving into vue.js and I've encountered a challenge. I want to pass the value of a rel attribute from an image to a method, but so far I have been unsuccessful. Here is the HTML code snippet: <template> <div> ...

Tips for encoding and transmitting floating-point data to GLSL from JavaScript/THREE.js and interpreting the output

I need assistance with encoding object positions (x,y,z) and sending them to a GLSL shader for decoding, performing calculations, and then returning the results back to the CPU. I have done some research on this topic and found some relevant resources like ...

Can you stop an image from being chosen on a website?

I have a website that features a table with text descriptions in the headers and question mark images (users can hover over them for help). Recently, I received a request to allow users to highlight and copy the table without including the images (using c ...

Does Three.js have a concept similar to an origin point?

I am curious to know if there is a concept similar to an origin point in three.js like we have in Blender. I have been researching this topic without any luck. I am working on creating a pinball game and it is crucial that the origin point of the paddle ...

TypeError: The function cannot be performed on the value of 0 in the Array.from

I encountered a peculiar error while attempting to utilize Array.from with Array.prototype.map. let fn = Array.from.bind(Array); // [Function: bound from] fn('test') // [ 't', 'e', 's', 't' ] ['test ...

Notifications for AngularJS tabs

I need help finding a method to incorporate "tab notification" using AngularJS, in order to show that there are important alerts that require attention. For example: (1) (3) TAB_ONE TAB_TWO TAB_THREE Could you provide any recom ...

Traverse through an array or object using recursive render functions in JavaScript

Here is an example of the issue I am currently trying to solve: https://codepen.io/wombsplitter/pen/KyWKod This is the structure of my array: [{ //obj 1 link: [{ //obj 2 link: [{ //obj 3 }] }] }] The ...

What are the steps to resize the "append-outer-icon" in Vuetify?

Is there a way to adjust the size of the icon when using it as "append-outer-icon"? <div> <v-col cols="12" > <v-text-field class="mx-8" v-model="message4" ...

Utilizing the v-for directive to loop through JSON data with unique IDs and linking them to Input components in PrimeVue

In my database, I have a collection of products with a column named attributes that stores property/value pairs in JSON format. Each product can have unique attributes. For instance, one product's attributes could be: #product1 attributes { color: & ...

"Issue with Material-ui Autocomplete where the defaultValue does not function properly

The defaultValue was set to "Chairs" but it doesn't seem to be working as expected. Here is the code snippet: import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomple ...

Choose the text that appears in the input or textbox field when tapping or clicking on it

Desperately Seeking a Clickable Textbox The Quest: In search of a cross-browser textbox/input field that can select its content on click or tap. An elusive challenge haunting developers for years. The Dilemma: Using a touch device triggers the tap e ...

Looping in jQuery to dynamically generate form field JS code

Here is the HTML & JS code for form submission. The code works as expected, but I am looking to simplify the JavaScript by using a loop iteration. The only difference between 'Full Name' and 'Booking Ref no.' is the ID and Class names. ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Tips for sending a form without reloading the page in node.js and ejs

<form action="" method="post"> <div class="bottom_wrapper clearfix"> <div class="message_input_wrapper" id="eventForm"> <input class="message_input" name="msg" placeholder="Type your message here..." /> </div ...

Obtain the elements within a rectangular region of a webpage

Exploring how to identify a specific subset of DOM elements within a webpage that fall within the boundaries of a defined rectangle, given two points as reference. Currently developing a web gallery where each photo is enclosed within an li tag. Planning ...

transform an array to an array consisting of objects

Below is an array list that needs to be converted into a specific form. var data = [ "USA", "Denmark", "London"]; The desired format for the array is: var data = [ { "id" : 1, "label": "USA" }, { "id" : 2, "label": "Denmark" }, { "id" : 3, "label": " ...

Executing Sequential Jquery Functions in ASP.Net

I have successfully implemented two JQuery functions for Gridview in ASP.Net 1. Enhancing Gridview Header and Enabling Auto Scrollbars <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script& ...

Tips for delaying my response in nodejs until the loop is complete

This is the code I'm currently working with: myinsts.forEach(function (myinstId) { Organization.getOrgById(myinstId,function (err, insts) { res.json(insts); }) }); I am using Node.js and encountering an error message that says "Can't set hea ...