Search code examples
vue.jsfirebase-authenticationvuex

vuejs vuex run action from action in store


I am trying to call fetchProfile on login and onauthstatechanged but none of these work.

this.fetchProfile()

this.store.dispatch("fetchProfile")

this.$store.dispatch("fetchProfile")

Im at a mental loss on this one. Not even console.logs in the fetchProfile runs, no evidence of the function running.

      actions: {
    authAction({ commit }) {
      firebase.auth().onAuthStateChanged(user => {
        console.log("Auth Changed");
        if (user) {
          commit("setUser", user);
          this.fetchProfile();
        } else {
          commit("setUser", null);
          commit("setProfile", null);
        }
      });
    },
    signInAction({ commit }) {
      console.log("Signing In");
      firebase
        .auth()
        .signInWithPopup(provider)
        .then(response => {
          console.log("got response");
          commit("setUser", response.user);
          this.fetchProfile();
          console.log("fetch?");
        })
        .catch(error => {
          commit("setError", error.message);
        });
    },
    signOutAction({ commit }) {
      console.log("Signing Out");
      firebase
        .auth()
        .signOut()
        .then(() => {
          commit("setUser", null);
          commit("setProfile", null);
          sessionStorage.clear();
        })
        .catch(error => {
          commit("setError", error.message);
        });
    },
    fetchProfile({ commit }) {
      console.log("fetching");
      firebase
        .firestore()
        .collection("profiles")
        .doc(this.getUser.user.uid)
        .get()
        .then(profile => {
          if (!profile.exists) {
            firebase
              .firestore()
              .collection("profiles")
              .doc(this.getUser.user.uid)
              .set({
                name: this.getUser.user.displayName,
                creationTime: this.getUser.user.metadata.creationTime
              })
              .get()
              .then(newProfile => {
                console.log("created user");
                commit("setProfile", newProfile);
                console.log(this.getProfile());
              });
          } else if (profile.exists) {
            console.log("User exists fetching profile");
            commit("setProfile", profile);
            console.log(this.getProfile());
          }
        });
    }
  }

Solution

  • You get access to dispatch from the first parameter, like commit.

    This should work:

    authAction({ commit, dispatch }) {
      firebase.auth().onAuthStateChanged(user => {
        console.log("Auth Changed");
        if (user) {
          commit("setUser", user);
          dispatch("fetchProfile");
        } else {
          commit("setUser", null);
          commit("setProfile", null);
        }
      });
    },