Search code examples
vue.jslogiclifecycle

Can I cache an API call object using Vue JS lifecycle hooks?


I'm using The Strain API which has a search query that gets all the strains in its database. It says to use this sparingly as it requires a lot of computing power. My question is: can I call it once in the App component life cycle hook, save the response in the App data(), and cache it somehow so that if the data.object.length != 0, it doesn't try calling it again? Then I could pass it as a prop to any other component that needs it. Sorry, new to VueJs and programming.


Solution

  • the best thing in my opinion is to keep the calculated data in a service, so that you in your mounted component simply call the getData (), imported from the StrainService.js

    // StrainService.js
    let response = null;
    
    
    const getData = async () => {
        if (!response) {
            response = await StrainApiCall()
        }
    
        return response
    }
    
    
    const StrainApiCall = () => {
        return axios.get('yourdata.com') // your api call
    }
    
    
    export {
        getData
    }