Search code examples
firebasevue.jsgoogle-cloud-firestorevuex

State won't completely mutate


I have this login system. When a user logs in, my action sets my state to data (username, email, and userId) I retrieve from firebase authentication and store in a variable called newUser, so I can access it and display some of it on the DOM. According to the console log in my vuex action, the info is stored in the variable just fine. However, when I console log the data in the file that's supposed to display the data, some of the data does not come through. The userId and email come through just fine, but the username comes through as undefined. What would cause this and how can I fix this?

Here's my code from where I'm handling the data:

  state: {
    user: null
  },

  mutations: {
    setUser(state, payload) {
      state.user = payload;
  },
    userLogin({ commit }, payload) {
      commit("setLoading", true);
      commit("clearError");

      firebase
        .auth()
        .signInWithEmailAndPassword(payload.email, payload.password)
        .then(user => {
          commit("setLoading", false);

          const signedInUser = {
            email: payload.email,
            id: user.user.uid,
            username: user.user.displayName
          };

          console.log(signedInUser);
          commit("setUser", signedInUser);
        })
        .catch(err => {
          commit("setLoading", false);
          commit("setError", err);
        });
    },

  getters: {
    user(state) {
      return state.user;
    }
  }

And here's how I'm attempting to access the data to check it and display it on the DOM:

  created() {
    console.log(this.$store.getters.user);
  },

  computed: {
    username() {
      return this.$store.getters.user.username;
  },

I've attempted to set my user as an empty array, an empty object, and as an object with the pieces of data I want to store explicitly stated, meaning:

user: {
    username: null,
    email: null,
    id: null
}

as well, and none of these methods worked.

Any help is greatly appreciated. Thank you ahead of time.


Solution

  • It should be this.$store.getters.user.username instead of this.$store.getters.username

      computed: {
        username() {
          const user = this.$store.getters.user
          if (user) {
             return user.username
          }
        }
      },