Cannot read properties of null (reading 'email')

Viewed 48

I am unable to fetch the current state that has been store in the component mounting stage. Here i have initialized a ref variable isAdmin, after that in the mounting stage I want to get the current user email from the state and check if its the same as the email that i want and then i want to toggle isAdmin "true". But when i am trying to access the email its saying email does not exist.

Here is have attached the vuex store on the right and from where i am accessing its on the left. check just above

Vuex store.js

import { createStore } from "vuex";
import router from "../router";
import { auth } from "../firebase";
import {
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signOut,
  onAuthStateChanged
} from "firebase/auth";

export default createStore({
  state: {
    user: null,
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user;
    },

    CLEAR_USER(state) {
      state.user = null;
    },
  },
  actions: {
    async login({ commit }, details) {
      const { email, password } = details;

      try{
        await signInWithEmailAndPassword(auth, email, password)
      } catch(error){
        alert(error)
        return
      }
      commit('SET_USER',auth.currentUser)

      router.push('/')
    },

    async register({ commit }, details) {
      const { email, password } = details;

      try{
        await createUserWithEmailAndPassword(auth, email, password)
      } catch(error){
        alert(error)
        return
      }
      commit('SET_USER',auth.currentUser)

      router.push('/')
    },

    async logout({commit}){
      await signOut(auth)

      commit('CLEAR_USER')

      router.push('/login')
    },

    fetchUser({commit}) {
      auth.onAuthStateChanged(async user => {
        if(user === null){
          commit('CLEAR_USER')
        } else {
          commit('SET_USER',user)

          if(router.isReady() && 
            router.currentRoute.value.path === '/login')
            {
            router.push('/')
          }
        }
      })  
    }
  },
});

Here is the new of the UI with the div that i want show only when that email matches new div

1 Answers

The fetchUser action is not finishing in time before you try accessing state.user.email in the mounted hook. Instead, make isAdmin a computed property that will set it's value as soon as state.user.email is updated (which itself should be a computed property according to vuex docs).

const userEmail = computed(() => {
  return store.state?.user?.email;
})
const isAdmin = computed(() => {
  return userEmail.value === "abc@hotmail.com"
})
Related