Tips for displaying the most recent data in Vue following a successful fetch operation

I have the following script to load data from the server after the page loads:


<script>    
    export default {    
        data() {
            return {
                imageDirectory: "../../images/",
                fileName: "img",
                extension: ".png",

                products:
                [
                   {
                      name: 'loading data',
                      imageUrl: require("../../assets/t1.png")
                   } 
                ]

            }
        },
        name: "ProductList",

        created: function () {

            this.fetchData();
        },
        methods: {
            fetchData: function () {
                $.ajax({
                    type: "GET",
                    timeout: 1200000,
                    url: 'api/test',
                    contentType: "application/json",
                    dataType: "text",
                    success: function (data) {
                        window.alert(data);

                        this.products = [{
                            name: 'success' + 'test',
                            imageUrl: require("../../assets/t1.png")
                        }]                    },
                    error: function (data) {

                        this.products = [{
                            name: 'failed' + 'test',
                            imageUrl: require("../../assets/t1.png")
                        }]   
                    }
                });


            }
        }

    }
</script>

After running this script, the alert window confirms that the data was fetched successfully. However, the product name does not update to "success test." The code snippet:

this.products = [{ name: 'success' + 'test', imageUrl: require("../../assets/t1.png") }]

is moved inside the created: function() as follows:


created: function () {
    this.products = [{
        name: 'success' + 'test',
        imageUrl: require("../../assets/t1.png")
    }] 

    this.fetchData();
}

and then the data gets updated correctly. The code for fetching data and updating it seems to be correct, so what could be preventing the data from updating as expected?

(Please note that the code for updating the data is a placeholder).

Answer №1

When defining your fetchData function, be mindful of using the 'this' keyword within the $.ajax() method. This can lead to confusion for the compiler regarding which object is being referenced. Consider the following refactor:

fetchData: function () {
           let component = this;
            $.ajax({
                type: "GET",
                timeout: 1200000,
                url: 'api/test',
                contentType: "application/json",
                dataType: "text",
                success: function (data) {
                    window.alert(data);

                    component.products = [{
                        name: 'success' + 'test',
                        imageUrl: require("../../assets/t1.png")
                    }]                    },
                error: function (data) {

                    component.products = [{
                        name: 'failed' + 'test',
                        imageUrl: require("../../assets/t1.png")
                    }]   
                }
            });


        }

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

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

jQuery problem with setting and redirecting users if cookie value is missing

On my home page, there is a script that checks two things when a user visits our site: If the screen size is less than 800 pixels, they are redirected to the mobile site. If they have previously visited the mobile site and selected "View Full Site," ...

Obtain data with matching JSON values in a REACT application

Recently, I received a JSON file that looks something like this: [ { "symbol": "A", "name": "Agilent Technologies Inc", "exchange": "NYSE", }, { "symbol": "AAC ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Coming back from retrieving data from an API

I'm having trouble with a function that performs a POST request to retrieve access tokens from an API. Although the function successfully prints the token to the console, I haven't been able to figure out how to properly parse and save the access ...

Securing JSON-based RESTful services

I am in the process of developing a web application, where I have established a clear separation between my "frontend" server using Lighttpd to serve index.html and javascript. My frontend, powered by Backbone.js, is connected to my Node.js backend webser ...

Obtaining MIME-TYPE from a Base 64 String: A Handy Guide

After receiving a base64 encoded string from the backend, I am decoding it in Javascript to display it on the browser. The content of this string could be any type of file such as .pdf, .img, .docx, .zip, etc. The base64 string I have does not contain th ...

Include a description in the cell of the table

I am struggling with adding a small description below one of the columns in my three-column table. I have tried using Grid, but so far, nothing has worked for me. Can anyone provide assistance? To give you a better idea, I have highlighted the desired res ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

Tips for resolving issues with the carousel container in bootstrap?

Is there a way to adjust the carousel box container in Bootstrap so that it remains consistent even with images of varying sizes? Currently, the box size changes based on the image dimensions when sliding through the carousel. Sample Code: <h1>Caro ...

Manage the angularJS user interface switch through an external event

I have implemented an AngularJS Material UI switch and I am looking to update its status based on an external event. This event occurs when a MQTT message is received on a specific topic that is published. To achieve this, I am utilizing a Node.js MQTT cli ...

Webpack auto-injects the incorrect path for main.js

Whenever I access my 2nd level URL localhost:8080/level1/level2, it always displays an error indicating that it cannot find the main.js file, which is automatically injected by webpack. Screenshots: ...

Eliminate set of dates utilizing a different set of dates

Utilizing the MultipleDatePicker plugin to enable selection of multiple dates within a year. I have incorporated a checkbox feature that, when checked, will automatically mark all Sundays in the calendar. However, an issue arises when unchecking the check ...

What is the best way to send and configure GET information when the characters in a URI surpass 5,000?

Currently, I am utilizing a Laravel blade template. However, I encountered an error in my code when the size of the textarea item is quite large. I'm in search of a solution to resolve this issue. Hey everyone! Can you guide me on how to successfull ...

Error encountered in Angular: FormBuilder provider not found

I am currently utilizing Angular 9. An error that I am encountering is as follows: No provider for FormBuilder This issue has been documented in numerous instances, with the common solution being to include the FormsModule in the app.module.ts file. F ...

Ajax request results in a 400 error code

Here is the structure of my Ajax call: function Submit() { var objectData = { email: $("#email").val(), firstName: $("#firstName").val(), lastName: $("#lastName").val(), loginMode: $("#login ...

When attempting to run HTML and JavaScript files locally, an error is encountered: "TypeError: The module name 'openai' is not resolving to a valid URL."

As a beginner in web development, I decided to follow a tutorial on creating a web application using the OpenAI API. The tutorial instructor runs the code in an environment called Scrimba, but I am working on my MacBook. This is how the app functions: it ...

Securing paths in NuxtJS

Hey there! I'm just getting started with nuxt and have set up the following routes: /home /dashboard /login My goal is to secure the /dashboard route only for users who are logged in and have a token stored in LocalStorage. The simplest solution ...

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...