I was testing firebase with hooks for the first time and came across the well known infinite loop issue.
I know there are many others questions that may be close to this one, but I'm still not able to get around this issue on this situation.
Here the code on App.js:
import React, { useState, useEffect } from 'react';
import { auth, createUserProfileDocument } from './firebase/firebase.utils';
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
auth.onAuthStateChanged(async userAuth => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.onSnapshot(snapshot => {
setUser({
user: {
id: snapshot.id,
...snapshot.data()
}
})
});
console.log(user);
} else {
setUser(null);
}
});
}, [user]);
return (
<div></div>
);
}
export default App;
Here the createUserProfileDocument function from firebase.utils.js:
export const createUserProfileDocument = async (userAuth, additionalData) => {
if (!userAuth) return;
const userRef = firestore.doc(`users/${userAuth.uid}`);
const snapshot = await userRef.get();
if (!snapshot.exists) {
const { displayName, email } = userAuth;
const createdAt = new Date();
try {
await userRef.set({
displayName,
email,
createdAt,
...additionalData
})
} catch (err) {
console.log('Error creating user', err.message);
}
}
return userRef;
};
In this case, how would I check if the onAuthStateChanged has actually changed? I get the impression the auth.onAuthStateChanged function triggers each time, generating that infinite loop..
Here the resources I checked that may be helpful:
Thank you in advance.