Utilize Auth.currentSession() every 5 minutes within Vuex Store for automatic session management

I have been developing an application that makes frequent requests to our API, however, sometimes these requests result in expired tokens.

I have explored different solutions such as calling Auth.currentSession and setting the header before sending the request. However, this approach does not work seamlessly as many of the libraries we utilize do not wait for Auth.currentSession to return the new token if the current one has expired.

It appears that the most effective solution is to manually invoke Auth.currentSession every 9 minutes and store the token in the Vuex store. Is it possible to implement this in the Vuex store.js?

import { createStore } from 'vuex'
import { Auth } from 'aws-amplify'


export default createStore({
  state: {
    session: null
  },
  getters: {

  },
  mutations: {
    setSession(state, value){
      state.session = value
    }
  },
  // This function will automatically refresh the token every 9 minutes.
  actions: {
    async refreshSession({ commit }){
      try {
        const session = await Auth.currentSession()
        commit('setSession', session)
      } catch (error) {
        console.log(error)
      }
    }

  },
  modules: {

  }
})

I would like this process to run automatically every 9 minutes without having to manually trigger it from other components.

Answer №1

To resolve this issue, I decided to implement a solution where I added a new action in the store.js file that triggers the Auth.currentSession function. Then, in the App.vue file, I set up an interval to dispatch the refreshSession event every 9 minutes.

store.js

import { createStore } from 'vuex'
import { Auth } from 'aws-amplify'


export default createStore({
  state: {
    session: null
  },
  getters: {

  },
  mutations: {
    setSession(state, value){
      state.session = value
    }
  },

  actions: {
    async refreshSession({ commit }){
      const session = await Auth.currentSession()
      commit('setSession', session)
    }
  },
  modules: {

  }
})

App.vue


  created(){
      this.sessionInterval = setInterval(() => {
        this.$store.dispatch('refreshSession');
      }, 540000);
  },

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

Error message: When attempting to destructure property 'nuxt' of 'this', a TypeError occurred because 'this' is undefined

When setting up my new Nuxt project, I followed the instructions provided on their website at https://nuxtjs.org/docs/get-started/installation. The process involved simply running npm init nuxt-app@latest <project-name>. However, after completing th ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

Is there a way to modify page URLs without causing a refresh, regardless of browser?

Despite my extensive searches on various online platforms, including stackoverflow, I have yet to come across a satisfactory answer to my question. While I find the window.history.pushState() and window.history.replaceState() methods quite user-friendly, ...

Deactivate input areas while choosing an option from a dropdown menu in HTML

I've been working on creating a form and have everything set up so far. However, I'm looking to disable certain fields when selecting an option from a dropdown list. For instance, if the "within company" option is selected for my transaction typ ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

Do not let CKEditor interact with widget content

Even though the HTML content within the aside tag is not editable, CKEditor still performs content filtering and removes tags while displaying hidden input fields. Here is the relevant HTML widget code: <aside class="widget widget-form" contenteditabl ...

Building a Python Lambda function that connects to an AWS HTTP API

In this resource, you can find a guide on how to create an HTTP API that triggers a Lambda function using a node.js runtime. I recently attempted the same process with a Python lambda using the following handler: def lambda_handler(event, context): r ...

What are the steps to set up ChartJS on a personal computer?

Currently, I am working on creating charts with ChartJS using the CDN version. However, I would like to have it installed directly on my website. After downloading ChartJS v4.1.1, I realized that it only contains typescript files. Since I cannot use TS fil ...

Show a persistent header once you scroll past a certain point using Bootstrap

Utilizing Bootstrap affix property to reveal a header after scrolling down by 100px has been successful for me. However, I encountered an issue when trying to set the opacity property to 0.0001, it works as expected. But when setting it to 0 or changing di ...

Analyzing latency in node.js through numerous requests

Is there a way to send multiple requests in a loop, and measure the time of each request? In PHP I'd do: require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); for ($i = 0; $i < 100; $i++) { $start = mic ...

What steps should I follow to initialize the generated code?

Is there a way to dynamically add elements that respond to click events after the Vue instance has been initialized? Using v-html to append to the DOM works, but the new v-on attributes are not processed, causing the buttons to be non-functional. <!D ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Transforming JSON data into a hierarchical tree structure in JSON format

I have a JSON treeData that I need to convert into a different format so that I can use a visualization library in JavaScript. treeData={ "leftNode": { "leftNode": { "leftNode": { "leftNode": { ...

Utilize the Masonry layout script on dynamically generated elements from AJAX requests

I have been implementing a Masonry script with the following code: var $container = $('.grid'); $container.imagesLoaded(function(){ $container.masonry({ itemSelector : '.grid-item', columnWidth : '.grid-sizer', ...

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...

What is the process for resetting the v-money form fields?

I am facing an issue with resetting monetary value fields in my vuetify v-form. I use v-money to mask the values inserted, but when attempting to reset the form using ".reset()" or by setting the values at the end of my function, the values are not being r ...

Does anyone have any sample code on processing JSON data from a URL using Modified JavaScript Value in Java?

Could anyone provide some examples on how to handle returned Json data using Modified JavaScript Value? Here is the specific data I require from the json url: { "result": { "data": [ { "name": "page1", "period": "dia", "values": [ { "value": 4, "end_time" ...

What is the best way to create pages that showcase 10 posts each?

Currently, I am facing a challenge with displaying 100 posts using the Fetch API on one single page. I am looking for a way to create separate pages where each page would showcase only 10 posts. Below is my existing JavaScript code: fetch('htt ...