"Utilizing Vuex: Fetch data from API when the first getter is accessed, and subsequently retrieve it from the local

I have a Vuex instance that is responsible for fetching data from an API. The initial access to the store should trigger a call to load the data from the API. Subsequent accesses should return the previously loaded data stored in store.empresas. This is the structure of my Vuex module:

import Empresas from '@/api/empresas'
import moment from 'moment'

export default {
  state: {
    loaded: false,
    lastLoadedDate: null,
    empresas: []
  },

  getters: {
    empresas: state => {
      if (!state.loaded || moment().diff(state.lastLoadedDate, 'minutes') > 30) {
        // Data was not yet loaded or it was loaded more than 30 minutes ago,
        // Should fetch from the API -> actions.carregarEmpresas()
        // Unsure how to proceed here
      } else {
        // Data already loaded
        return state.empresas
      }
    }
  },

  mutations: {
    setEmpresas (state, payload) {
      state.loaded = true
      state.lastLoadedDate = moment()
      state.empresas = payload
    }
  },

  actions: {
    carregarEmpresas ({ commit }) {
      Empresas.listar()
        .then(({ data }) => {
          commit('setEmpresas', data.empresas)
        })
    }
  }
}

The main reason for this setup is because I will be accessing the empresas data in various parts of my application and I want to avoid making repeated API calls.

However, implementing this logic inside the getter has posed a challenge. Is there a way to achieve this?

Answer №1

It seems like there may be a similar question here: Is it possible to dispatch actions from getters in Vuex. Take a look at the second response for potential assistance.

In general, it's not recommended to invoke actions within your getters. A better approach would be to trigger the action during the app's initial loading phase. This way, you can simply access the getter without incorporating any conditional logic.

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

Create a validation rule in yup that depends on an external condition

I am currently attempting to set a condition based on a prop that is passed to a VueJS object. After researching some solutions, I noticed they all focus on using .when. However, .when is typically used when you need to establish a condition based on anot ...

Leverage the power of JSON data in conjunction with HighCharts through

I'm struggling to understand the JSON format and HighCharts. Despite trying various techniques found on forums, I haven't been able to achieve the desired result. Here's my issue: 1- When clicking, an Ajax call is made to a PHP file that g ...

What is the best way to incorporate new data into localstorage in a React application?

My attempt to implement and add data into local storage has not been successful as it keeps updating the old data instead of adding new ones. Can someone please explain how to store an array of objects entered by a user in local storage using React JS? ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

The binding style in vue.js using the ternary operator is throwing an error: Unexpected token ']'

partNav = Vue.component('part-nav', { data: navItems: [ { subItems: [ {...} {....} ] } {...} # another object in navItems array ] template: ' <div v-for="(navIte ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...

What is the best way to extract the geometry information from a gltf object?

I've been using three.js to load a gltf file with the gltfloader, and now I'm trying to create a particle system. However, I'm having trouble getting the geometry object that I need. function initModel() { var planeGeometry = new THREE ...

Retrieve the response status using a promise

There is a promise in my code that sometimes results in an error response (either 400 or 403, depending on the user). I am trying to handle this situation by catching the response and implementing a conditional logic to execute different functions based on ...

When the button is clicked, send data using 'POST' method to the php file and fetch

<script> $(document).ready(function(){ $("#vE_rebtn").click(function{ var reverifyEmail = '<?php echo $_SESSION["verifyEmIPv"]; ?>'; $('#rE_rebtn').hide(); $('#re_ ...

general structure used to activate every page in vue 3

AppTopbar.vue <Dropdown v-model="selected" :options="storesLists" @change="onChange" optionLabel="name" :filter="true" /> onChange(event) { console.log(event.value.value); localSt ...

Using setTimeout with drag and drop functionality in HTML

I need a setTimeout function to be triggered only after dragging and dropping an image into a division, not before the drop occurs. ...

Unable to locate the root element for mounting the component in Cypress with React

I am currently testing my react app, which was created using create-react-app, with the help of cypress. Unfortunately, I encountered an error that looks like this: https://i.stack.imgur.com/xlwbo.png The error seems to be related to trying to fetch an ...

A guide on extracting split values and assigning them to individual variables

Currently, I'm working on a project utilizing node.js, express, mongo, and socket.io. After successfully retrieving geolocation coordinates and storing them in a hidden input field, I encountered an issue when attempting to save the data into the data ...

Understanding the differences between paths and parameters of routes in express.js

My express application has the following routes: // Get category by id innerRouter.get('/:id', categoriesController.getById) // Get all categories along with their subcategories innerRouter.get('/withSubcategories', categoriesControll ...

Prevent left click on HTML canvas and enable right click to pass through with pointer-events

In my scenario, I have an HTML canvas positioned above various other HTML elements that detect right-click mouse events. The goal is to be able to draw on the canvas with the left mouse button while simultaneously interacting with the underlying HTML eleme ...

Only incorporate the Angular service into the controller when it is necessary

When attempting to incorporate lazy loading for angular services, controllers, directives, and filters, I discovered a way to achieve something similar using RequireJS. However, I am struggling to find a way to dynamically load a service into a controller ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

Preserving the initial input values in a secure manner for future reference, utilizing either an object or a

Recently, I've started revisiting a script I created a while back that checks for changes in a form to prompt a message asking 'Would you like to save your changes?'... One thing that's been on my mind is whether I should store the ori ...

"Strategies for using Selenium in Python to simulate clicks without relying on class, id, or name attributes

I am currently attempting to locate the "X" button and click on it, but I am struggling to find a way to do so. Below is the HTML code for the element: <div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: ...

webpack: the necessity of running TSC before resolving modules manually

Below is my complete webpack.config.js file for reference. If I delete all the *.js files in the app directory, webpack throws the following error: ERROR in ../main.ts Module not found: Error: Can't resolve './app/app.module' in 'C ...