Using Vue.js 2 to fetch a prop value from an API using http.get prior to the component being mounted

My goal is to fetch data from my server and use that data to populate a prop or data in vuejs.

Essentially, I am looking to pass the fetched data as a parameter of my component.


data() {
    return {
        resources_data : [
            { id: 'a', title: 'Room A' },
            { id: 'b', title: 'Room B', eventColor: 'green' },
            { id: 'c', title: 'Room C', eventColor: 'orange' },
            { id: 'd', title: 'Room D', eventColor: 'red' }
        ],
        my_resources: []
    }
},
methods: {
    getServerData: function() {
        var self = this;
        Vue.http.get('/admin/getResources').then((response) => {
            _.forEach(response.data.resources,function(item){
                self.my_resources.push(item);
            });
            console.log(self.my_resources);
            return self.my_resources;
        });
    },
},
mounted() {
    const cal = $(this.$el),
        self = this;

    self.getServerData();

    cal.fullCalendar({
        header: this.header,
        defaultView: this.defaultView,
        editable: this.editable,
        selectable: this.selectable,
        selectHelper: this.selectHelper,
        aspectRatio: 2,
        slotDuration: '00:10:00',
        timeFormat: 'HH:mm',
        eventSources: self.eventSources,
        events: self.events,
        resources: self.resources_data,
        fixedWeekCount: false,
        firstDay: 1
    });
}

I am struggling with retrieving data from a URL in vuejs. I have tried using computed, props, and method, but none seem to be working...

Is there a way to retrieve data directly from the server response instead of relying on the hardcoded variable resources_data? Any tips or suggestions would be greatly appreciated!

Answer №1

Your issue may be related to the interaction between fullCalendar and your asynchronous method. It is advisable to initialize fullCalendar after receiving the data.

Have you considered returning the promise from your getResources method?

methods: {
    getResources: function() {
        var self = this;
        return Vue.http.get('/admin/getResources').then((response) => {
            _.forEach(response.data.resources,function(item){
                self.my_resources.push(item);
            });
        });
    },
},

mounted() {
    const cal = $(this.$el),
        self = this;

    self.getResources().then(() => {
        cal.fullCalendar({
            header: this.header,
            defaultView: this.defaultView,
            editable: this.editable,
            selectable: this.selectable,
            selectHelper: this.selectHelper,
            aspectRatio: 2,
            slotDuration: '00:10:00',
            timeFormat: 'HH:mm',
            eventSources: self.eventSources,
            events: self.events,
            resources: self.my_resources,
            fixedWeekCount: false,
            firstDay: 1
         });
    });
 }

Alternatively, you could directly call fullCalendar within the getResources method.

getResources: function() {
    var self = this;
    return Vue.http.get('/admin/getResources')
        .then((response) => {
            _.forEach(response.data.resources,function(item){
                self.my_resources.push(item);
        })
        .then(() => {
            $(this.$el).fullCalendar({
                header: this.header,
                defaultView: this.defaultView,
                editable: this.editable,
                selectable: this.selectable,
                selectHelper: this.selectHelper,
                aspectRatio: 2,
                slotDuration: '00:10:00',
                timeFormat: 'HH:mm',
                eventSources: self.eventSources,
                events: self.events,
                resources: self.my_resources,
                fixedWeekCount: false,
                firstDay: 1
             });
        })
    });
}

If preferred, you can postpone mounting the component until the data has been retrieved.

Answer №2

The solution lies in adjusting your perspective: it's not possible.

To navigate this challenge, you must shift your mindset. Each component should react dynamically and showcase itself based on its model. Interrupting the component during data retrieval from the server is not an option. Consider these two approaches:

  1. Handle the "data not ready" state by presenting a loading indicator or an empty list. Whether you are modifying data internally or receiving props from the parent component, introduce a flag like dataReady to track when the AJAX request is complete. Utilize this flag in your template with an if statement to show either the loading indicator or the actual data.
  2. Manage the component's display within its parent component and reveal it only after the data has been successfully fetched.

There are no alternative solutions available.

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

Guide to converting a form into a structured object format (with a tree layout)

Looking to transform a form into an object structure? <form> <input type="text" name="Name" /> <input type="checkbox" name="Feature.Translate" /> <input type="checkbox" name="Feature.Share" /> <input type="submi ...

The data being retrieved from the controller in AngularJS is not displaying as expected

Just started learning AngularJS. Currently following this MEAN Stack Intro: Build an end-to-end application Created a basic html file to test angularjs. index.html <html> <head> <meta charset="utf-8"> <title> ...

The sequence of Request and Response in Express

When using the Express app.get() method, does the order of writing response and request matter? For example, is there a difference between app.get("/", (req, res) => and app.get("/", (res, req) =>? ...

JavaScript and PHP/HTML template engine technology

I've recently discovered the jQuery template engine and am intrigued by its potential. It seems to be very efficient for ajax calls, as the data exchange is minimized. However, when I initially load my application using only PHP and HTML to display ...

Please ensure that all fields in the form are filled out before clicking the enable button

Is it possible to enable the button only when all fields are filled out in a form? It's easy if there's just one field, but I have multiple fields with a select field as well. I'm not sure how to do this. Here's the form I've creat ...

What is the best way to stack a canvas box on top of another canvas box?

My goal is to have two canvas squares stacked on top of each other. While I am familiar with drawing on canvas, I need assistance in placing one canvas on top of another. Despite my attempts at setting the position, I have not been successful. <canvas ...

Loading page with asynchronous JavaScript requests

As I send my AJAX request just before the page loads and then call it on the same page afterwards, here is what it looks like: <input type="text" class="hidden" id="storeID" value="<?php echo $_GET['store']; ?>"> $(document).ready(fu ...

When setting a value through the DOM, the input's value bound with ngModel in Angular does not get updated

Trying to upload a file to calculate its hash and display it in an input box. If done correctly, the value should show in the form, but when submitting the form, the value does not get sent. Only adding a blank space by clicking on the input field works: ...

use jquery to implement select all checkbox feature in django

Is there a way to automatically select all checkboxes when clicking on the top checkbox? Here is my code snippet: run.html <script language="JavaScript" src="media/js/jquery-1.4.2.min.js"></script> <script language="javascript"> $("#sel ...

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...

Unable to display content within .vue file

My Index.vue file includes the following code, however, it is not displaying properly. <div> test </div> <script> export default { // } </script> ...

JavaScript scripts are not functioning properly in a partial view following a refresh

Issue: The partial view contains JavaScript scripts that work when first loaded, but stop working after being loaded a second time. Description: I have a partial view reloading on value change in a select box (which calls this function). @(Html .DevE ...

Using an image tag with dual quotes in Vue.js

I am currently working on a feature where users can upload an image and then have it displayed after the upload is complete. However, I am facing an issue where the response link of the image contains a double quote, and when I use the <img> tag to ...

The issue of Bootstrap icons not displaying on the front-end arises when integrating them into a Vuejs Template

I'm in the process of constructing a web application using Vue.JS. I've integrated the [Bootstrap Icons][1] into my application, but for some reason, the icons are not showing up on the screen. Here are the steps I followed: Installed Bootstrap ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

encountering a problem with iterating through a JSON array

After making an ajax call and retrieving select options in json format, I implemented the code below to display these new options in place of the existing ones: success: function (data){ var $select = $('#dettaglio'); $select.html(' ...

In Electron, methods for detecting and resolving Error TS2304: Unable to locate the name 'unknown on(event: 'ready', listener: (launchInfo: unknown) => void): this are essential for smooth operation

Encountering an issue while running npm build. Electron version: 7.1.2 TypeScript version: ^2.5.1 Target version: ES2017 Here are the details of the error. When I performed the build under the following conditions: Electron version: 6.0.0 TypeScript ver ...

Tips for decreasing the width of a Grid component in React using MUI

Is there a way to adjust the width of the initial Grid element within Material UI, allowing the remaining 3 elements to evenly occupy the extra space? see visual example Would modifying the grid item's 'xl', 'lg', 'md', ...

Updating the authentication code in passport.js

In the project, there is a passport.js file that contains authentication related code: const axios = require('axios') const uuid = require('uuid/v4') const passport = require('passport') const LocalStrategy = require('pa ...

Creating dynamic pages using user input in Node and Express

Currently, I am facing a challenge in rendering text using node/express. Within my project setup, there is an HTML file containing a form. The file named search.ejs looks like this: $(document).ready(function(){ var userInput; $("#submit-button-i ...