Skip to content

Instantly share code, notes, and snippets.

@gragland
Last active March 5, 2024 20:05
Show Gist options
  • Save gragland/4ccd86d4685db33b2c422af0159774a4 to your computer and use it in GitHub Desktop.
Save gragland/4ccd86d4685db33b2c422af0159774a4 to your computer and use it in GitHub Desktop.
How to lazy load Firebase with dynamic imports
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} />
);
}
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
Copy link

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.

const checkAuthState = async () => {
    const firebase = await getFirebase()

    await firebase.auth().onAuthStateChanged(user => {
        setFirebaseUser(user)
    })
}

useEffect(() => {
    checkAuthState()
}, [])

@gragland
Copy link
Author

gragland commented Jul 16, 2021

@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());
}, []);

@SoldierCorp
Copy link

That did the trick, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment