Home > OS >  Auto Refresh for Vuex
Auto Refresh for Vuex

Time:05-19

I would like to implement a auto refresh feature for my VueX store.

Everything the user refresh their browser, an actions in VueX store will be triggered to load the user profile from API call.

Is't possible to achieve that?

import apiService from "@/services/apiService";
import apiUrls from "@/services/apiUrls";

import { getToken } from "@/services/jwtService";

// Code to run actions when user refresh
getToken() !== null ? this.actions.getUserProfile() : "";

const state = {
  userProfile: {},
};

const getters = {
  userProfile: (state) => state.userProfile,
};

const actions = {
  async getUserProfile({ commit }) {
    console.log("here");
    try {
      let response = await apiService.get(apiUrls.PROFILE);
      commit("setUserProfile", response.data.data);
    } catch (error) {
      console.log(error);
    }
  },
};

Thank you.

CodePudding user response:

A user refresh means that the application will be re-executed. So basically main.js will be re-executed, App.vue re-created, etc.

That means just have to call your code in main.js or in a created lifecycle hook of any top-level component.

By top-level component I means any component which is created early in the app

  • Related