Last active
March 5, 2024 20:05
-
-
Save gragland/4ccd86d4685db33b2c422af0159774a4 to your computer and use it in GitHub Desktop.
How to lazy load Firebase with dynamic imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import getFirebase from "./firebase.js"; | |
function MyApp() { | |
// Example function that wraps some firebase logic | |
const onSignup = async (email, password) => { | |
// Use await to ensure firebase library is loaded | |
const firebase = await getFirebase(); | |
// Call firebase methods as you normally would | |
const { user } = await firebase.auth() | |
.createUserWithEmailAndPassword(email, password); | |
// Do something with `user` | |
router.push(`/user/${user.uid}`); | |
} | |
return ( | |
<Signup onSubmit={onSignup} /> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getFirebase = async () => { | |
// Lazy load Firebase core (must come first) | |
const { default: firebase } = await import("firebase/app"); | |
// Lazy load Firebase services you need | |
await Promise.all([ | |
import("firebase/firestore"), | |
import("firebase/auth"), | |
]); | |
// Make sure not already initialized | |
if (!firebase.apps.length) { | |
firebase.initializeApp(config); | |
} | |
return firebase; | |
}; | |
export default getFirebase; |
@SoldierCorp Yeah good question. You need to get the unsubscribe function returned by onAuthStateChanged
when it resolves. As you probably already know, that's made trickier by the fact you can't use async/await within useEffect
. Something like this should work:
useEffect(() => {
const promise = getFirebase().then((auth) => {
return auth.onAuthStateChanged((user) => {
setFirebaseUser(user);
});
});
// Unsubscribe after promise has resolved
return () => promise.then((unsubscribe) => unsubscribe());
}, []);
That did the trick, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
How can I unmount or cancel the subscription with a code like this:
This code is within a file that is a ProtectedRoute with react-router to check if I have a session or not but I am receiving the warning
Can't perform a React state update on an unmounted component.