Minimize the number of axios requests made every time a Vue component is displayed

I am relatively new to Vue, so please bear with me as I may not have all the knowledge in this area.

  1. Within one of my child components (Product_Collection.vue), I am making an axios request to retrieve products from my Shopify store using their GraphQL API:

    data: () => {
     return {
       products: null
     }
    },
    methods: {
     getProducts: function(){
       // 1. axios code here...
       // 2. ...then assign result to "this.products" data property 
     }
    }
    
  2. The products are displayed as thumbnails (let's say there are 10 t-shirts). When I click on a product, I want to view it in more detail with additional information and images, similar to the experience on Amazon.

  3. The product is then shown individually in a Product_Single.vue component. So far, everything seems to be working fine.

However, here lies the issue...

  1. When I navigate back to the products page (Product_Collection.vue) (the page displaying the 10 t-shirts), the axios request to the Shopify API is triggered again, causing the component to be re-rendered from scratch.

My question is how can I instruct Vue to refrain from fetching data from the Shopify API every time the component is rendered? Thank you for your help.

Answer №1

It seems like you are interested in implementing cache-control, a feature that Axios conveniently supports through an extension.

https://github.com/kuitos/axios-extensions

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    // enabling cache by default
    adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // actual HTTP request sent
http.get('/users'); // response retrieved from cache without making another HTTP request
http.get('/users', { cache: false }); // manually disabling cache triggers a new HTTP request

Alternatively, you could create your own caching mechanism by storing results in an object and managing data expiration manually. However, using cache-control headers and expiry provided by the API eliminates the need to handle stale data within the application.

Answer №2

If Vue Router is not in use and you need to conceal the list page, consider utilizing a straightforward alternative.

Opt for v-show over v-if. This allows the component to be concealed and revealed without being recreated.

Furthermore, when do you make the API call? Do you do so within the created or mounted hook?

Answer №3

If you're working with GraphQL, consider utilizing the Apollo state management method which seamlessly integrates with GraphQL. Take a look at this resource: https://dev.to/n_tepluhina/apollo-state-management-in-vue-application-8k0

Instead of rewriting the application using axios and incorporating Vuex into the mix, Apollo client may offer a more convenient solution.

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

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. https://i.sstatic. ...

What could be causing my HTML elements to shift position based on varying screen sizes or zoom levels?

Does anyone else experience their HTML and CSS elements shifting around based on the screen size or zoom level? I have screenshots illustrating this issue. Here is how it currently appears And here is how it's supposed to look ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

What is the reason for the initial display of an empty option when using AngularJS to select an

Every time I refresh the page, the initial option is blank. How can I set Any Make as the default selection? Below is the code snippet from my view: <select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-chan ...

What is causing the TypeError when trying to set a property on undefined in AngularJS?

I've taken on the challenge of building a microblog app to learn more about angularJS. One thing that's really getting me is trying to understand the differences between service, factory, and provider. After some research, I decided to go with s ...

Tips for Designing a Custom Footer Layout for KoGrid

Is it possible to create a footer template for a koGrid that displays the sum of a column? gridOptions : { displaySelectionCheckbox: false, data: items, // selectedItems: self.selectedItems, multiSelect: false, ena ...

A guide to resolving the Postgres issue: "The bind message provides 8 parameters while the prepared statement "" only needs 6."

In my backend setup, I am working on preparing my model. I have tab1 which contains id and col: t1 that I want to insert into first, then get its id and insert it into my tab2 along with other cols. The foreign key from tab1 (id_tab2) is used in tab2 (whic ...

Vue: Load page content only after the route change is complete

Every time I visit a new route within the current session, I notice that the page loads and then takes about 2 seconds for the styles to be applied. This delay causes what is commonly known as CSS flashing or FOUC (Flash of Unstyled Content), which ultimat ...

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

What are the steps to effectively implement the useEffect hook in React?

I'm facing an issue where I am trying to return a function that utilizes useEffect from a custom usehook, but I keep getting the error "useEffect is called in a function which is neither a react function component nor a custom hook." Here's what ...

Application route is failing to direct to the HTML page

On my MEAN stack website, I am trying to make the browser navigate to a file named 'findCable.html' but it keeps directing to 'singleCable.html'. I have double-checked the angular routing file and backend routes, but can't see ...

Experience the magic of MFA Firebase combined with the seamless flow of React

I'm currently in the process of integrating Multifactor authentication with Firebase for a user enrollment, using the setup guide available at: https://cloud.google.com/identity-platform/docs/web/mfa I'm encountering difficulties in understandin ...

Updating checkboxes in Vue.js

I'm struggling a bit with VueJS states. Here is the setup for my simple app: new Vue({ el: '#media-app', data: { activeTypes: [], activeCategories: [], medias: [] }, methods: { getFilteredDat ...

Tips for streamlining the transfer of essential features from a main project to its duplicate projects

In my Angular project, I have a core repository on GitHub that serves as the foundation for custom client projects. Each time a new client comes onboard, we create a clone of the core project and make customizations based on their requirements. The issue ...

Encountering an issue while attempting to generate a dialog popup with jQuery

As a beginner in jQuery, I am attempting to implement a popup dialog box for users in case of an error. However, I'm encountering issues with the following jQuery code: <script type="text/javascript"> $(document).ready(function() { var $dia ...

Guide on how to clear and upload personalized information to Stormpath

After receiving JSON data from my client, I am looking to store it in Stormpath's custom data using node.js with express.js: I have set up a basic post route: app.post('/post', stormpath.loginRequired, function(req, res){ var data = req.b ...

Is it possible to send a server response without requiring a callback function to be provided from the client side?

Clarifying the Issue When utilizing .emit() or .send() with a desire to confirm message reception (referred to as acknowledgements), the syntax typically involves: socket.emit('someEvent', payload, callback); The focus of this discussion is on ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects var obj1={ "name":"mayur", "age":23 } var obj2={ "name":"keyur", "age":29, "limit":54, "surname":"godhani" } //I am familiar with one approach var j1 = {name: 'Varun', age: 24}; var j2 = {code: &ap ...