Leveraging a single Axios request across various components

My current setup involves making a simple Axios call in this way:

.get('https://myAPI.com/')
  .then(response => {
    this.info = response.data
  })

Subsequently, I utilize a v-for array loop on my components to display the retrieved data. However, the issue arises from repeatedly running this mounted Axios call on every component where it is used.

For instance, one of my components for desktop screens employs this axios call to showcase data in a sidebar, while another component for mobile screens also uses the exact same axios call for displaying information in a header.

The dilemma lies in the fact that multiple calls are being made to the same API due to each component implementing the mounted axios function separately.

Is there a strategy available to execute this call just once and then apply the v-for loop on each individual component?

Answer №1

If you need to manage state in your Vue project, consider using Vuex.

Here is a simple example to get you started: Install Vuex and axios in your project.

Create a file named store.js within your project directory.

store.js

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

const store = new Vuex.Store({
  state: {
    info : []
  },
  mutations: {
    updateInfo (state, info) {
      state.info = info
    }
  },
  actions: {
    fetchData({commit}) {
      axios.get('https://myAPI.com/')
       .then(response => {
         commit('updateInfo', response.data )
      })
    }
  }
})

In your main.js, import the store.js file.

import store from "./store";

new Vue({
  ...
  store,
  ...
});

In your App.vue, dispatch the 'updateInfo' action.

App.vue

  ...
  created() {
    this.$store.dispatch("fetchData");
  }
  ...

To access the info data component in any component, set it up like this:

...
computed: {
  info() {
    return this.$store.state.info
  }
},
...

You can use the info array to render elements using the v-for directive.

This info refers to the array of elements fetched from the API.

Answer №2

Alright, I have come up with a solution to manage this situation without relying on Vuex. Let me explain with an example involving two components: TrainingCourseComponent and CertificateComponent.

For the TrainingCourseComponent:

 data() {
     return {
        trainings : {},
     },
methods:{
       loadTrainingCenters(){
         axios.get("/trainingCourse")
         .then(({data}) => {
         this.trainings = data;
         Event.$emit('globalVariables', data);
         });
       }
}
 created(){
        this.loadTrainingCenters();          
        }

Similarly, you can implement this in any other component like CertificateComponent (you can define it within mounted() or created() method):

 data() {
            return {
                training_courses:{}
            }
 }
 mounted(){
          Event.$on('globalVariables', (trainings) => {
            this.training_courses = trainings;
          });
        }

By the way, just as a reminder, Event is a global Vue instance defined in app.js that I utilize for various purposes :)

app.js

 /**
   * custom event handling
   */

  window.Event = new Vue();

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

Is there a way to check if a file name input is valid using regular expressions?

I'm having trouble getting my code below to work properly. I'm not sure if the problem lies in the match function syntax or the regex itself. Any assistance would be greatly appreciated. $scope.fileSelected = function (file) { var valid = "/ ...

Error: Failed to clone an object in Electron due to an unhandled promise

I'm in need of assistance with sending files from the main directory to the renderer. Before proceeding, I attempted to check if it was functioning correctly by using console.log(files). However, this resulted in an error message. Can someone please p ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Is there a way for me to choose multiple checkboxes simultaneously?

I have a dynamically created HTML table with checkboxes added for each row. $.each(data, function(id, value) { rows.push('<tr><td><input type="checkbox" autocomplete="off" class="chkbox" name="chkbox" value="'+value.site+' ...

Values in Local Storage are not located upon first attempt, but after a reload they function properly

import {useEffect} from 'react'; import {useRouter} from 'next/router'; const AuthenticationGuard=props=>{ const {children,fallback} = props; const auth = useAuth(); const router=useRouter(); useEffect(()=>{ if(!r ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Create custom components by wrapping npm components and exporting them as a single custom component

Encountering issues while installing 3rd party components from npm. For instance, a dropdown react module that can be used easily in my own module; however, I find myself needing to declare its style and other dependencies in multiple modules. For example ...

What is the process for generating an API endpoint in Next.js that includes a query string?

I am currently working on setting up an API endpoint in Next.js, specifically the following one: /api/products/[name]?keyword=${anykeyword}. To accomplish this, I understand that I have to create it within the pages/api/products/[name] directory in index ...

Tips for implementing controlled components in Vue to update values in the parent component object

Utilizing controlled components, I am able to emit the selected value. For example, // app-select.vue <v-select :items="[1,2,3]" @change="$emit('input', $event)"></v-select> // parent-component.vue <app-sele ...

I am experiencing an issue with my React app deployed on Heroku where it successfully loads the home page but fails

My react application performs perfectly when run locally and is successfully deployed on heroku. However, upon clicking any link from the home page to another page, a blank page with 'not found' message appears. No other error messages are displa ...

Incorporating a classList.toggle into a snippet of code

button, p, h1, h2, h3, h4, h5, a{ /* Define specific elements to use "fantasy" font */ font-family: Tahoma; } #main_body{ margin: 0px auto; background-color: #dedede; } #top_body{ /* Remove margin for simplicity */ } #t ...

Updating a table in Javascript after deleting a specific row

Is there a way to automatically reindex rows in a table after deleting a row? For example, if I delete row 1, can the remaining rows be reordered so that they are numbered sequentially? function reindexRows(tableID) { try { var t ...

best practices for data flow between components in React using hooks

I have successfully retrieved data from my database in the Recipes component. Now, I am attempting to pass this data into the RecipeList component. However, when I do so, only the bullet points are showing up in the RecipeList component and for some reas ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Empty body detected in Jquery AJAX request with Django REST running in a Docker environment

Using JavaScript to load a template called index.html from the /static directory. The JavaScript code in app.js: var obj = new Object(); obj.startTime = "123"; obj.endTime = "456"; console.log("fetchNext "+JSON.stringify(obj)); v ...

Basic AngularJS application, however I am receiving {{this is supposed to be the information}}

Building an angularjs app I have set up an asp.net mvc4 application and integrated the angularjs package using nuget. The Layout.cshtml file has been updated to look like this: <!DOCTYPE html> <html ng-app="myApp"> <head> <meta ...

CSS swapping versus CSS altering

Looking to make changes to the CSS of a page, there are two methods that come to mind: Option 1: Utilize the Jquery .css function to modify every tag in the HTML. For instance: $("body").css("background : red") Alternatively, you can disable the current ...

Is it possible to create a THREE.js form using a sequence of outlines?

Consider the scenario where three two-dimensional shapes are present. To keep things simple, let's envision them all as circles: Is there a method in THREE.js that allows for these shapes to be 'stacked' on top of each other vertically, res ...

What is the process for adding a download link to my canvas once I have updated the image?

Is it possible to create a download link for an image that rotates when clicked, and then allows the user to download the updated image? Any help would be appreciated.////////////////////////////////////////////////////////////////////// <!DOCTYPE ht ...