Vuex empty state on login

My vuex state is reset/cleared on user sign out (using vuex-extensions). This is so that when a new user signs in, the state is populated with new information and there is no residue from the previous user’s state.

The state is cleared correctly on signout (using store.reset()), but the issue is when a user signs out and a new user signs in, the state is empty and they have to refresh the page or click on a random component to get vuex to load in the data into the state and have the getters display data in the components.
I checked the console and it seems like the actions indeed get fired on user login, but for some reason the data is not shown in the components, unless the page is refreshed.
Why is this happening and how can I fix this ?

Vuex store.js

import Vue from 'vue';
import Vuex from 'vuex';
import { Auth } from 'aws-amplify';
import axios from 'axios';
import { createStore } from 'vuex-extensions'

var AWS = require('aws-sdk');
var AWSCognito = require('amazon-cognito-identity-js');

Auth.currentUserInfo


Vue.use(Vuex);

const weatherService = {

    state: () => ({
        error: null,
        loading: false,
        // current
        currentWeather: Object,
        wind_speed: '',
        wind_degree: '',
        clouds: '',
        latitude: '',
        longitude: '',
    }),
    mutations: {
        SET_WEATHER_DATA(state, payload) {
    
            state.wind_speed = (payload.current.wind_speed * 3.6).toPrecision(2) + ' km/h';
            state.wind_degree = payload.current.wind_deg + '°'
        },
    },
    actions: {
        GET_WEATHER_DATA({ commit, state }) {
            this.ddb_data = [];
            var self = this;

                userPool = new AWSCognito.CognitoUserPool(data);
            var cognitoUser = userPool.getCurrentUser();

            try {
                state.loading = true
        
                        AWS.config.credentials.get(function (err) {
                            if (!err) {
                                var id = AWS.config.credentials.identityId;
                                // Instantiate aws sdk service objects now that the credentials have been updated
                                var docClient = new AWS.DynamoDB.DocumentClient({
                                    region: AWS.config.region,
                                });
                                var params = {
                                    TableName: 'XXXXXXX',
                                    KeyConditionExpression: '#user_id = :userid',
                                    ExpressionAttributeNames: {
                                        '#user_id': 'userid',
                                    },
                                    ExpressionAttributeValues: {
                                        ':userid': id,
                                    },
                                };

                                params.ProjectionExpression = 'user_meta_data';



                                docClient.query(params, function (err, data) {
                                    if (err) console.error(err);
                                    else {
                                        self.ddb_data = [...data.Items];
                                        const latitude = self.ddb_data[0].user_meta_data.coordinates.latitude
                                        const longitude = self.ddb_data[0].user_meta_data.coordinates.longitude


                                        axios
                                            .get(
                                                '        https://api.openweathermap.org/data/2.5/onecall?lat=' +
                                                latitude +
                                                '&lon=' +
                                                longitude +
                                                '&exclude=minutely' +
                                                '&units=metric&APPID=' +
                                                process.env.VUE_APP_OPEN_WEATHER_API_KEY
                                            )
                                            .then((response) => {
                                                commit('SET_WEATHER_DATA', response.data)
                                                state.loading = false

                                            })
                                            .catch((error) => {
                                                console.log(error);
                                            });


                                    }
                                });
                            }
                        });
                    });
                }
            } catch (e) {
                console.log(e);
                return;
            }

        },

    },

    getters: {
        weatherGetter(state) {
            return state;
        },
    }
};


const store = createStore(Vuex.Store, {
    modules: {
        w: weatherService
    },
    state: {
        authorized: false,
        user: null,
        currentTemp: '',
        loginError: '',
        signupError: '',
        confirm: false,
        confirmError: '',
        latitude: '',
        longitude: '',
        coordinates: Object,
        user_ddb: Object,
        button: Boolean,
        // loadedCattle: [],
        ddbGetData: [],
        loadCattleAWSCognito: [],


    },
    mutations: {

        SET_COORDINATES(state, payload) {
            state.coordinates = payload
        },

        user(state, user) {
            // state.authorized = !!user && user.attributes && user.attributes.email_verified
            state.authorized = !!user && user.attributes
            state.user = user
        },
        confirm(state, showConfirm) {
            state.confirm = !!showConfirm
        },

    },

    actions: {
        DDB_GET_DATA({ commit }) {
            try {
                                var params = {
                                    TableName: 'XXXXX',
                                    KeyConditionExpression: '#user_id = :userid',
                                    ExpressionAttributeNames: {
                                        '#user_id': 'userid',
                                    },
                                    ExpressionAttributeValues: {
                                        ':userid': id,
                                    },
                                };

                                params.ProjectionExpression = 'user_meta_data';

                                docClient.query(params, function (err, data) {
                                    if (err) console.error(err);
                                    else {
                                        const coord = {
                                            latitude: parseFloat(data.Items[0].user_meta_data.coordinates.latitude),
                                            longitude: parseFloat(data.Items[0].user_meta_data.coordinates.longitude)
                                        }
                                        const user_data = {
                                            username: data.Items[0].user_meta_data.user.username
                                        }

                                        commit('SET_COORDINATES', coord)


                                    }
                                });
                            }
                        });
                    });
                }
            } catch (e) {
                console.log(e);
                return;
            }

        },

        //  Authentication
        async login({ dispatch, state }, { email, password }) {
            state.loginError = ''
            try {
                await Auth.signIn(email, password);
            } catch (err) {
                console.log(`Login Error [${err}]`)
                if (err)
                    state.button = true
                state.loginError = err.message || err
                return
            }

            await dispatch('fetchUser')

        },

        async authState({ commit, dispatch }, state) {
            if (state === 'signedIn')
                await dispatch('fetchUser')
            else
                commit('user', null)
        },


        async fetchUser({ commit, dispatch }) {
            try {
                const user = await Auth.currentAuthenticatedUser()
                const expires = user.getSignInUserSession().getIdToken().payload.exp - Math.floor(new Date().getTime() / 1000)
                console.log(`Token expires in ${expires} seconds`)
                setTimeout(async () => {
                    console.log('Renewing Token')
                    await dispatch('fetchUser')
                }, expires * 1000)
                commit('user', user)
            } catch (err) {
                commit('user', null)
            }
        },
        async logout({ commit }) {
            await Auth.signOut()
            commit('user', null)
            store.reset()
        },

    },

    getters: {

        getCoordinates(state) {
            return state.coordinates;
        },
        getUser(state) {
            return state.user;
        },

    },


});




export default store;

component.vue

<template>




      <span id="weather">{{ weatherX.uv }}</span>
      <span id="weather"> {{ weatherX.wind_speed }} </span>
      <v-spacer></v-spacer>

          <v-list>
            <v-list-item>
              <v-list-item-title v-if="user">{{
                user.attributes.email
              }}</v-list-item-title>
            </v-list-item>

            <v-list-item v-if="user" @click="logOut">
              <v-list-item-icon>
                <v-icon>mdi-logout</v-icon>
              </v-list-item-icon>
              <v-list-item-title>Sign out</v-list-item-title>
            </v-list-item>

          </v-list>
        </v-menu>
      </v-btn>
    </v-toolbar>
  </v-card>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  data() {
    return {
    };
  },

  computed: {
 
    weatherX() {
      return {
        wind_speed: this.$store.state.w.wind_speed,
        wind_degree: this.$store.state.w.wind_degree,
      };
    },
    user() {
      return this.$store.getters.getUser;
    },
  },
  methods: {
    ...mapActions({
      GET_WEATHER_DATA: 'GET_WEATHER_DATA',
    }),
    async logOut() {
      await this.$store.dispatch('logout');
      this.$router.push('/login');
    },
  },
  mounted() {
    this.GET_WEATHER_DATA();
  },

};
</script>

67 thoughts on “Vuex empty state on login”

  1. Pingback: stromectol 12mg
  2. First of all I would like to say excellent blog!
    I had a quick question in which I’d like to ask if you do not mind.
    I was interested to know how you center yourself and clear your thoughts before writing.
    I’ve had a hard time clearing my thoughts in getting my thoughts out there.
    I do take pleasure in writing but it just seems like the first 10 to 15 minutes are usually lost just trying to
    figure out how to begin. Any recommendations or tips?

    Cheers! https://buszcentrum.com/deltasone.htm

    Reply
  3. Pingback: ivermectin in usa
  4. Pingback: otc generic viagra

Leave a Comment