Не получается обновить getter, используя vuex
Мне нужно, чтобы обновился геттер isUserSignedIn. В моём понимании я делаю всё правильно - делаю await, чтобы посмотреть обновился ли массив. Логика: сначала пользователя регистрирует, потом отправляется письмо на почту с верификацией, пользователь подтверждает и возвращается обратно и заходит спокойно в профиль, в моём же случае страницу после подтверждения нужно обновить - хотелось бы от этого избавиться.
Вывод в консоли:
User data fetched: {email: '[email protected]', phoneNumber: '*', isAdmin: false, isVerified: false, displayName: 'name name', …}
<script>
import useValidate from "@vuelidate/core";
import useValidationRules from "@/firebase/Validations/RegisterValidationRules.js";
import {
updateUserProfile,
checkIfFirstUser,
registerWithEmailAndPassword,
sendEmailVerify,
} from "@/firebase/Authentication/EmailAuth/index.js";
import { showErrorToast, showInfoToast } from "@/firebase/Toasts";
import { mapActions, mapGetters } from "vuex";
export default {
name: "RegisterFormComponent",
setup() {
const { state, rules } = useValidationRules();
const v$ = useValidate(rules, state);
return {
state,
v$,
...mapGetters(["isUserSignedIn"]),
};
},
methods: {
...mapActions(["setIsLoading"]),
async registerUser() {
// Check if form has validation errors
this.v$.$validate();
if (this.v$.$error) {
showErrorToast("Form has validation errors!");
return;
}
try {
// Check if user is the first user
const isFirstUser = await checkIfFirstUser();
const displayName = `${this.state.firstName} ${this.state.lastName}`;
// Prepare user data
const userData = {
email: this.state.email,
phoneNumber: this.state.phoneNumber,
isAdmin: isFirstUser,
};
this.setIsLoading(true);
// Register user with email and password
const userCredential = await registerWithEmailAndPassword(
this.state.email,
this.state.password.password
);
await updateUserProfile(userCredential.user, displayName, userData);
await sendEmailVerify(userCredential.user);
showInfoToast(
`Please verify your email address to proceed. A verification email has been sent to ${this.state.email}.`
);
do {
await this.$store.dispatch("fetchUserData");
await new Promise((resolve) => setTimeout(resolve, 1000));
} while (!this.$store.getters.isUserSignedIn);
this.navigateToProfilePage(true);
} catch (error) {
switch (error.code) {
case "auth/email-already-in-use":
showErrorToast(
"Email is already in use. Please use a different email address."
);
break;
case "auth/invalid-email":
showErrorToast("Invalid email address.");
break;
case "auth/invalid-password":
showErrorToast(
"Invalid password. Password must be at least 6 characters long."
);
break;
case "auth/operation-not-allowed":
showErrorToast(
"Email/password accounts are not enabled. Please contact support."
);
break;
case "auth/too-many-requests":
showErrorToast(
"Too many registration attempts. Please try again later."
);
break;
default:
showErrorToast(
"Error occurred during registration. Please try again later."
);
console.error(error.code);
}
} finally {
this.setIsLoading(false);
}
},
navigateToProfilePage(registered) {
this.$router.push({
name: "AppProfile",
query: { registered },
});
},
},
};
</script>
Само хранилище:
import { createStore } from "vuex";
import { getCurrentUser } from "@/firebase/firebase";
import { signOutUser } from "@/firebase/Authentication/SignOut";
export default createStore({
state: {
userData: null,
isLoading: false,
showVerifyEmailMessage: false,
},
mutations: {
setUserData(state, userData) {
state.userData = userData;
if (userData && userData.isVerified) {
console.log("User is verified");
}
},
setIsLoading(state, isLoading) {
state.isLoading = isLoading;
},
},
actions: {
async fetchUserData({ commit }) {
try {
const userData = await getCurrentUser();
commit("setUserData", userData);
console.log("User data fetched:", userData);
return userData;
} catch (error) {
console.error("Error fetching user data:", error);
throw error;
}
},
async signOut({ commit }) {
try {
await signOutUser();
commit("setUserData", null);
} catch (error) {
console.error("Error signing out:", error);
}
},
setIsLoading({ commit }, isLoading) {
commit("setIsLoading", isLoading);
},
},
getters: {
isUserSignedIn: (state) =>
state.userData !== null && state.userData.isVerified,
isAdmin: (state) => state.userData !== null && state.userData.isAdmin,
userDataLoaded: (state) => state.userData !== null,
isLoading: (state) => state.isLoading,
},
});
Файл инициализации firebase:
import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { onSnapshot, doc } from "firebase/firestore";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: process.env.VUE_APP_API_KEY,
authDomain: process.env.VUE_APP_AUTH_DOMAIN,
databaseURL: process.env.VUE_APP_DATABASE_URL,
projectId: process.env.VUE_APP_PROJECT_ID,
storageBucket: process.env.VUE_APP_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_MESSAGING_SENDER_ID,
appId: process.env.VUE_APP_APP_ID,
measurementId: process.env.VUE_APP_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const storage = getStorage(app);
const getCurrentUser = () => {
return new Promise((resolve, reject) => {
onAuthStateChanged(
auth,
async (user) => {
if (user) {
try {
const userRef = doc(db, "users", user.uid);
onSnapshot(userRef, (docSnapshot) => {
if (docSnapshot.exists()) {
const userData = {
...docSnapshot.data(),
isVerified: user.emailVerified,
displayName: user.displayName,
id: user.uid,
};
console.log("User data fetched:", userData);
resolve(userData);
} else {
reject(new Error("User data not found"));
}
});
} catch (error) {
reject(error);
}
} else {
resolve(null);
}
},
reject
);
});
};
export { auth, db, storage, getCurrentUser };