(Vuejs, Vuetify) Best practices for preventing duplicate object loads from an API

As a beginner in Vuejs, I am working on a website that displays content fetched from the backend to the frontend. To achieve this, I am using Axios to connect to the API with the following code snippet:

    contentList: [],
};
const mutations = {
    setContent (state) {

            axios
            .get("http://backendapi/content")
            .then(res => {
              const data = res.data;
              for (let key in data) {
                const object = data[key];
                state.contentList.push(object)
              }
            });
    }
};
const actions = {
    initContent: ({commit}) =>{
        commit('setContent');
    }
};

When my page loads, I populate the content list as follows:

mounted() {
    this.$store.dispatch('initContent');
    this.content = this.$store.getters.contentList
  }

However, I am facing an issue where every time I navigate away and return to the page, the content in the list gets duplicated. Can someone guide me on how to improve this code to prevent double loading of content?

Thank you!

Answer №1

Before sending a request, always check if the content is already on your list.

setContent (state) {
    if (state.contentList.length == 0){
        axios
        .get("http://backendapi/content")
        .then(res => {
          const data = res.data;
          for (let key in data) {
            const object = data[key];
            state.contentList.push(object)
          }
        });
    }
}

If you prefer to update the content every time, ensure that the variable is reset each time.

axios
        .get("http://backendapi/content")
        .then(res => {
          const data = res.data;
          let contentList = [];
          for (let key in data) {
            const object = data[key];
            contentList.push(object);
          }
          state.contentList = contentList;
        });

Answer №2

Make sure to verify if the data has already been loaded before making an axios call. The purpose of this action is to trigger the axios call:

const mutations = {
    updateData (state, newData) {
       state.dataList = newData 
    }
};
const actions = {
    async fetchData: ({commit, state}) =>{
        if (state.dataList.length === 0) {
          try {
            let result = []
            let response = await axios.get("http://api/data")
            for (let key in response.data) {
               result.push(response.data[key])
            }
            commit('updateData', result);
          } catch (error) {
             // handle errors
          }
        }
    }
};

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

"Utilizing jQuery Mobile's Pagebeforeshow event with the advanced functionality of longlist

Currently, I am utilizing JQuery mobile version 1.0.1. To set up a page, the following code is utilized: <div data-role="page" id="homecomments"> <div data-role="header"> <h1>Comments</h1> <a href='#home&apo ...

What is the speed of retrieving new data once it has been inserted into a firebase real-time database?

In the midst of developing my personal project using next.js, I've encountered an issue with a component that includes a getstaticprops function. This function scrapes a website and then posts the extracted data to a firebase realtime database. Howeve ...

Adding external JSON data to a plain HTML document can be achieved through the process of

I have been experimenting with extracting data from an API in JSON format, but I am struggling to figure out how to convert the JSON tags into HTML elements. You can view a sample of the JSON data here. Does anyone know how to transform this JSON into DI ...

Operating PHP program from html on Beaglebone Black Rev C Debian

I've created a JavaScript program that utilizes node.js to manage GPIO from an IO.html page to the beaglebone. I simply initiate the JavaScript with "node myscript.js". Now, I'm looking to incorporate a PHP file that will store data from the IO. ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

Prevent Scrolling of Body Content within a Specified Div

In my current situation, I am dealing with a large number of divs (over 300) that are being used as part of an interactive background. The issue arises when viewing the page on mobile versus desktop – there are too many divs on desktop, causing excessive ...

Steps for automatically closing a TextPrompt if the end user does not respond within a specific time frame

How can I programmatically close a Prompt in Microsoft Chatbot SDK v4, such as TextPrompt or ConfirmPrompt, and end the dialog after a certain period of time if the user does not reply? I attempted to use setTimeout and step.endDialog but encountered issu ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

Error: JSON parsing error encountered for token < at position 0 within the context of Google Sheets Apps Script Tutorial

I'm currently working through a Google Sheets Apps Scripts editor tutorial and I've reached module 4. Unfortunately, I've encountered an issue with the code I copied directly from the module. The error message I'm seeing is: SyntaxError ...

Managing numerical data in a CSV file using JavaScript and Google Visualization Table

A JavaScript snippet provided below will load a CSV file named numericalData.csv, which contains headers in the first row and numerical values starting from the second row. The data is then displayed using a Google Visualization Table. I am looking to con ...

Guide on organizing a multi-dimensional array of objects based on property value using javascript?

I am faced with the challenge of sorting a multidimensional array based on values, but the selection is dependent on the parentID. This is my current array: const result = [ [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}], [{ ...

I am encountering an issue where the object I am sending with Next.js is appearing as undefined on the receiving page

When transferring data from my question screen to a result screen, I am using an object called footprintsData. Here is the code snippet for sending the data: const footprintsData = { carFootprint: roundedCarFootprint, electricityFootprint: roundedElect ...

Vue failing to render content from data object

I recently started using NuxtJs and decided to create a new file named test.vue within the pages directory. Below is the code snippet from my test.vue file: <template> <div> <h1 style="font-size: 30px">{{ message }} </h1> ...

Error message: The agent encountered difficulties in printing all of the results obtained from the Axion library request in Dialog

My goal is to display all the results obtained from the following request (the initial code is not functioning): function searchForProducts(agent) { // category_name = 'Cooking' for example const category_name = agent.parameters.category_na ...

The compatibility issue between Express Session and Vue.js using Axios is causing issues

The initialization of the session in express.js also utilizes passport.js for local authentication, which is functioning properly. However, there seems to be an issue with the session/cookie not working. app.use(serveStatic(__dirname + '../../dist&a ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

How to utilize a defined Bootstrap Modal variable within a Vue 3 single file component

I'm diving into the world of TypeScript and Vue 3 JS. I created a single-file-component and now I'm trying to implement a Bootstrap 5 modal. However, my VSCode is showing an error related to the declared variable type. The error message reads: ...

Looping through multiple AJAX calls

I have come across numerous questions on this topic, but I am still struggling to find a solution that will make my code function correctly. There is a specific function for calling AJAX that I am unable to modify due to security restrictions. Here is how ...

Generating charts using JSON data with the help of JavaScript

Hi there! I have a JSON file shown in the first image and I would like to create a chart similar to the one in the second image using JavaScript (using any library). Can anyone provide me with a simple example code on how to achieve this? ...

What are some ways I can customize the appearance of this Google Maps infoWindow?

I was able to create a Google Maps script using JavaScript code. The map displays multiple locations with corresponding latitude and longitude coordinates. This script can be viewed at . My objective now is to customize the appearance of the info windows ...