As a newcomer to Next.js and Firebase, I embarked on creating a login system with roles recently. Leveraging Firebase Authentication, I stored account roles in Firestore and linked the authentication account with Firestore data by utilizing the UID as the Document ID.
Note: While uncertain if this is the optimal approach, I've been successful in retrieving data from a field by referencing the Document ID acquired through the UID.
The goal is to extract the account's role from Firestore and apply it within a function to redirect users to appropriate pages based on their role. The issue arises when my pushToPage() function executes before getData() retrieves the necessary information from Firestore.
This is the LogIn function, where I employ auth.onAuthStateChanged to obtain the user's UID:
var firebaseDocument = ' ';
var accountType = '';
var databaseRef = '';
function LogIn() {
signInWithEmailAndPassword(auth, email, password)
.then((response) => {
sessionStorage.setItem('Token', response.user.accessToken);
auth.onAuthStateChanged((user) => {
if (user) {
firebaseDocument = user.uid;
databaseRef = doc(database, 'users', firebaseDocument);
} else {
console.log('User logged out');
}
});
})
.catch((err) => {
console.log(err.code);
});
accountType = getData();
pushToPage(accountType);
}
The following is the getData function responsible for fetching the account role:
const getData = async () => {
try {
const docSnap = await getDoc(databaseRef);
if (docSnap.exists()) {
return docSnap.data().account_type;
} else {
console.log('Document does not exist');
}
} catch (e) {
console.log(e);
}
};
This snippet showcases the pushToPage function which utilizes the accountType variable to determine the redirection destination:
const pushToPage = (accountType) => {
if (accountType == 'management') {
router.push('/accounts/management');
} else if (accountType == 'dean') {
router.push('/accounts/deans');
} else {
router.push('/accounts/faculty');
}
};
Upon running this code, besides experiencing delays due to awaiting the Firebase response, an error message surfaces:
Unhandled Runtime Error
FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
Oddly enough, I did not utilize collection() at any point.
I've attempted to research similar issues and concluded that integrating a .then() function or some form of Asynchronous Programming technique may be necessary. Unfortunately, comprehending these concepts proves challenging for me.
Any assistance provided here would be greatly appreciated. Thank you all.