Call Auth.currentSession() At 5 minute intervals in Vuex Store

Viewed 17

I'm working on an app where I do alot of requests to our API, and sometimes the request end up with expired tokens.

I looked into different solutions like calling Auth.currentsession and setting the header before sending the request, but that doesn't work so well since alot of the libaries we use don't "await" Auth.currentsession to return the new token if the current one is expired.

It seems the best solution is to manually call Auth.currentsession at 9 minute intervals and store the token in the vuex store, Is this possible to be done 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 want this to run automatically every 9 minutes without me having to call anything from my other components.

1 Answers

My solution was to create an action in the store.js file that calls Auth.currentsession, and in the App.vue file 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);
  },

Related