Can Vue.js automatically refresh the display when there are changes in a third-party JSON file?

I'm attempting to achieve a specific goal using Vue, but I'm uncertain if it's feasible given my current struggles in obtaining the desired outcome:

An API endpoint returns an array containing multiple objects.

While I am able to successfully render this data in my Vue application, I am curious if Vue has the capability to "track" updates to the array and automatically display new objects in the view.

Currently, I use setInterval to perform a GET request every 10 minutes, updating the object within my data() as intended. However, these changes are not reflected in the view.

To trigger a re-render, I toggle a boolean value from true to false at the start and end respectively, forcing the view to update with v-if.

My objective is to create a straightforward Twitter feed app that periodically fetches tweets via a GET request every 10 minutes, populates them into my Vue instance, and displays them in the view without requiring page reloads or component re-renders - essentially an automatic Twitter feed continuously loading new tweets every 10 minutes.

Is this achievable? I've experimented with utilizing Vue's Vue.set() method but haven't observed any impact.

If this approach isn't viable, what would be an alternative way to implement similar functionality?

Below is the provided code snippet:

JavaScript:

new Vue({
  el: '#app',
  data: {
    items: [],
  },
  created() {
    this.load();
    setInterval(() => this.load(), 5000);
  },
  methods: {
    load() {
      axios.get('https://reqres.in/api/users?page=2')
      .then(response => {
        this.items = response.data.data;
      });
    }
  }
});

HTML

<div id="app">
  <p v-for="item in items">
    {{ item.first_name }}
  </p>
</div>

CodePen: https://codepen.io/tomhartley97/pen/VwZpZNG

In the presented code, instances where the array is updated through the GET request fail to exhibit changes in the view?

Answer №1

Absolutely, it can be done. The method to add new reactive properties in your Vue instance is as follows:

For Object properties:

Vue.set(this.mainObject, key, value)
The mainObject cannot be a Vue instance or the base data() object, so you need to create a separate container property.

When dealing with Array entries, utilize native array methods such as Array.prototype.push(). Using Vue.set(array, index, element) does not have the desired effect.

Your implementation could resemble this:

<script>
export default {
  data() {
    return {
      response: [],
    };
  },

  mounted() {
    setInterval(() => this.fetchData(), 600000);
  }

  methods: {
    async fetchData() {
      const results = await getData();
      const resultLength = results.data.length;
      for (let i = 0; i < resultLength; i++) {
        const entryExists = this.response.some((entry) => {
          return entry.id === results.data[i].id
        })
        if (!entryExists) {
          this.response.push(results.data[i]);
          // To make nested Objects reactive, they need to be set explicitly
          // e.g. Vue.set(this.response[this.response.indexOf(results.data[i])], nestedKey, results.data[i].nested)
        }
      }
    }
  }
};
</script>

Answer №2

Upon reviewing the codepen, it became clear why your view is not updating: the API response consistently returns the same array!

To resolve this issue, try fetching and returning different data from the API.


Since the API returns an array, you can define the data as follows:

data() {
  return {
    array: [] // This array will store the API data
  }
}

Your template should resemble the following structure:

<div v-for="item in array">
</div>

Here are the update methods to continuously fetch new data:

update() {
  setInterval(async () => {
    let resp = await api()

    this.array = resp.data.concat(this.array)

  }, TEN_MINUTES)
}

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

Error message in JavaScript saying "The response string is undefined

I am working on a program built in angularjs. Currently, I receive JSON data from the server when online, but I am now developing an offline mode for the application. Despite trying to tackle the issue, I am unable to identify why I cannot resolve it. In ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

I am currently experiencing some difficulties with displaying posts on my website. This issue arises because I am utilizing the vue.js framework within my laravel

I am facing an issue with my app.js file. The response is supposed to be displayed on the console, but instead, I am encountering an error which I cannot seem to figure out. require('./bootstrap'); window.Vue = require('vue'); Vue.co ...

Implementing Pagination Functionality Using Knockout.js

Sample JSON Data [{ "name": "A Goofy Movie (1995) 720p HDTVRip x264 Eng Subs [Dual Audio] [Hindi DD 2.0 - English DD 2.0] Exclusive By -=!Dr.STAR!=-", "progress": 0, "size": "1.06 GB", "downloaded": "87.98 KB", "hash": "8fe65e43464debe ...

Avoid consistently updating information

I am experiencing a strange issue in my project. I have 2 tabs, and in one tab, there are checkboxes and a submit button. The user selects items from the checkboxes, and upon clicking the button, they should see their selections in the other tab. This fu ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

Fascinating CSS rendering glitch observed on zooming in: all browsers create a noticeable gap between containers except for Firefox

I'm experiencing a rather intriguing and peculiar issue with css styles when zooming in and out on the browser. Specifically, I've created a material ui card where the background-color changes upon clicking with an animation effect. The animati ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

Sending bulk SMS with Twilio using Node.js - A step-by-step guide

I am seeking guidance on how to send SMS notifications to multiple numbers using Twilio. I have a String Array with different phone numbers and would like to be able to send the same message to all of them. Here is an example of what I'm trying to ach ...

The tagging feature in ui-select isn't working properly, showing an error message that says "Cannot read property 'length' of undefined"

Looking to set up a ui-select for keyword tagging. Initially, when adding a new tag everything works fine, but after removing all tags and adding a new one, I get the error: Cannot read property 'indexOf' of undefined Check out the demo here ...

Tips for causing the JavaScript confirm alert to appear just a single time

My latest project involves creating a confirm alert that notifies users when their password is about to expire, prompting them to change it. The functionality for this alert is located in the header section of the website. Upon successful login, users are ...

Unexpected behavior encountered with Angular module dependency injection

Having some difficulty managing dependencies for my node app. Here's the current structure: app.js var app = angular.module('myApp', ['myController', 'myFactory', 'rzModule', 'chart.js', 'myServ ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Adapting CSS styles according to the height of the viewport

Goldman Sachs has an interesting webpage located here. One feature that caught my eye is the header that appears as you scroll down, with squares changing from white to blue based on the section of the page. I'm curious about how they achieved this ef ...

Obtaining the current ID from a URL in an API using Axios with Vue.js

When the user clicks the button, I want them to be able to block another user. This means that the URL should have a dynamic value for the user's id: http://example/user/:id. This is my template: <template> <div class> <div ...

Tips for conducting performance analysis in React 16

In the React documentation, it is mentioned that react-addons-perf does not function with React 16 and suggests using Chrome's built-in tools for equivalent functionality. However, in my experience, I have not found this to be true. For example, let& ...

JSON Novice - persistently storing data in JSON during browser refreshes

My AJAX poll was set up following a guide found here: http://www.w3schools.com/php/php_ajax_poll.asp Instead of storing the poll entries from an HTML radio button in an array within a text file as demonstrated in the tutorial, I wanted to save them in a J ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Is there a way to programmatically select an HTML tab or filter in puppeteer?

I am currently developing a web scraping application for a website that utilizes tab headers to filter the contents of a table. In order to extract the data from the table, I need to first select a specific filter by clicking on a tab item. However, I&apos ...

Creating a CSS Grid with Scroll Snap functionality to mimic an iPhone screen in HTML

I have created an iPhone simulator using HTML. It's in German, but I can provide a translation if needed: // JavaScript code for various functionalities related to the iPhone interface /* CSS styling for the iPhone interface */ <meta name="v ...