Search code examples
javascriptvue.jsvuejs2vue-componentvuex

How to redirect user to home page if user is authentic i.e ID or PASSWORD is correct in vue.js using VUEX STORE state?


I am setting user authenticity in VUEX Store state if user id and password are valid. But how would I access this in my signIn.vue to redirect?

If user is valid then set VUEX store state i.e isUserAuthentic to true For this I've used computed properties. to get user state i.e isUserAuthentic and work around in hasUserSignedIn in computed properties. I'm checking if user is authentic then redirect and return undefined from this computed properties. So that I can use this in HTML and doesn't affect HTML because I'm returning undefined from that computed properties. It is working but that's not perfect/best practices.

SignIn.vue

<template>
    <section>
        <div class="form-wrapper">

            //--------------------------------------USING COMPUTED PROPERTIES
            {{ hasUserSignedIn }}
            
            <input v-model="email"/>
            <input v-model="password"/>

            <button class="btn-signin" @click="submit()">
                sign in
            </button>
        </div>
    </section>
</template>

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

export default {
  data() {
     email: '',
     password: '',
  },
  methods: {
    submit() {

      if (this.email && this.password) {
        this.$store.dispatch('signInUser', { email: this.email, password: this.password });
      }
    },
    redirectTohome() {
      this.$router.push({ path: '/home' });
    },
  },

  computed: {
    ...mapGetters(['isUserAuthentic']),

    //-----------------------------------------WORKAROUND COMPUTED PROPERTIES
    hasUserSignedIn() {
      if (this.isUserAuthentic) {
        this.redirectTohome();
      }
      return undefined;
    },
  },
};
</script>

VUEX signin.js

import Vue from 'vue';
import axios from 'axios';

// const URL = 'http://localhost:3000';

const state = {
  signInLoading: false,
  isUserAuthentic: false,
};

const getters = {
  isSignInLoading: (signInState) => signInState.signInLoading,
  isUserAuthentic: (signInState) => signInState.isUserAuthentic,
};

const mutations = {
  SET_SIGNIN_LOADING_STATUS(signInState, status) {
    signInState.signInLoading = status;
  },
  SET_USER_AUTHENTICITY(signInState, isAuthentic) {
    signInState.isUserAuthentic = isAuthentic;
  },
};

const actions = {
  async signInUser({ commit }, payload) {
    // SET LOADING STATUS TRUE
    commit('SET_SIGNIN_LOADING_STATUS', true);

    try {
      // AUTHORIZE USER WITH AXIOS
      const response = await axios.post(`${URL}/api/v1/user/signin`, payload);

      // IF USER IS AUTHENTIC, SET AUTHENTIC STATUS TO TRUE
      if (response.status === 200) {
        commit('SET_USER_AUTHENTICITY', true);
      }
    } catch (e) {
      // SEND TOAST NOTIFICATION TO USER FOR INVALID REQUESTS
      if (e.response && e.response.data.message) {
        Vue.$toast(e.response.data.message, {
          type: 'info',
          timeout: 8000,
        });
      } else {
        Vue.$toast('Something went wrong, Please try again.', {
          type: 'error',
          timeout: 8000,
        });
      }
    }

    // SET LOADING STATUS FALSE
    commit('SET_SIGNIN_LOADING_STATUS', false);
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
};

Solution

  • I read the docs and I think WATCHERS are much better than COMPUTED in this particular case.

    In this approach we don't have to use {{ hasUserSignedIn }} in HTML. Just watch the property and when it is true redirect to home.

     watch: {
        isUserAuthentic(val) {
          if (val) {
            this.redirectTohome();
          }
        },
      },
    

    If someone have better solution, You are more than welcome