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

Exploring portfinder in Javascript: A guide to its usage

As a newcomer to Javascript, I am eager to figure out how to utilize the portfinder.getPort() function within one of my functions in order to generate a random port each time. The code snippet below showcases my current implementation: var portfinder = re ...

The ternary operator, also known as the conditional operator

One feature I have implemented is a button that can generate a random color and update the color state with this value. The color state is then used to define the background color of the div. Within the div, there is a lock/unlock button that toggles the ...

A convenient Delete Modal Component in React utilizing Reactstrap

I am currently working on implementing a reusable Delete Component using reactstrap, which can be called from other components. Below is the code for my DeleteModal: class DeleteModal extends Component { constructor(props) { super(props); this. ...

Steps for evaluating a Vue Component method invocation in an asynchronous function

Having trouble properly mocking my methods in this scenario. I have a component with two methods; name: 'MyComponent', methods: { async submitAction(input) { // does await things // then ... this.sh ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...

Placement Mismatch of Radio Button in Form.Check Component of React-Bootstrap

Recently, I've been working on implementing a payment method feature where users can choose their preferred payment option using radio buttons. However, there seems to be an issue with the alignment of the button. Below is the code snippet I have so ...

What are the steps for implementing a heatmap in Vue Highcharts?

Struggling with error 17 while attempting to use a heatmap chart type in vue-highcharts. I've searched online and it appears that importing and correctly using it may solve the issue. Can someone guide me through this process as there seems to be no d ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...

Convert form data into a JSON object utilizing JQuery and taking into account nested JSON objects

Currently, I am facing an issue while extracting data for submission using the jQuery `serializeArray()` function. This function works efficiently by providing an array of { name: value } objects, where the name corresponds to the elements in the form. How ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

Navigating up and down effortlessly using bootstrap

My webpage has a collapsible form located near the bottom, but when it's opened users must scroll down to see all of it. Is there a way to automatically scroll down when it's opened and then scroll back up when closed? Take a look at my code: & ...

Generate a PDF document on the user's device

Is there a way for me to trigger the print command on a PDF file without relying on Adobe PDF viewer's print button? I'm interested in using a separate event instead of the print button within the PDF viewer. Is this achievable? ...

Implementing ngFor to Iterate Through a JSON Object in Angular 6

Iterate through the object list retrieved from a JSON object Here is the JSON object that I have fetched: { "0": { "0": null, "1": "Consolidated Statements of Changes in Stockholders\u2019 Deficit", "2": null, "3": "", "4": "" ...

Challenges with pjax/ajax and handling the browser's back button

I've implemented pjax to ajaxify my menu links, which works well until I encounter an issue with the browser back button. In my JavaScript file, I have both Common Script files (to load all necessary js files when the user hits the URL) and Script fil ...

Expand Menu Options (jQuery)

Currently facing a jQuery problem that I can't seem to figure out. I've set up a menu with submenu elements and want to toggle the content height by clicking on menu items. The issue arises when clicking on another item causes the content to coll ...

Obtain a byte array from an AngularJs controller

In my Angular controller, I am working with a byte array. When the download button is clicked in the view, I want to trigger the browser's download/saveAs dialog with 'report.pdf' as the pre-populated filename and PDF as the file type. After ...

Argument for setInterval function

As a newcomer to programming, I am attempting to develop a basic javascript game. I have encountered an issue with the window.setInterval function and it seems to be causing everything to malfunction. I have been following a tutorial at this link and att ...

Unable to retrieve scope data in controller function

Having trouble accessing the scope attribute fullName from the controller method login. What could be causing this issue? App.controller('LoginController', ['$scope', 'LoginService', '$location', function(scope, Log ...

Improve navigation by integrating jQuery validation to resolve input errors seamlessly

I have been working with the jQuery validation plugin and Bootstrap. I recently added a fixed navigation bar at the top of the page using Bootstrap CSS. However, I encountered an issue where the fixed navigation was overlapping with the error message for i ...

Techniques for animating background image using jQuery

Hello there! I'm currently experimenting with animating a background image using jQuery. Despite following a tutorial, I haven't been successful in getting my test page to work as intended. The blue Facebook icon displays, but it doesn't ani ...