I've been having some trouble integrating Firebase into my app using the useFireBaseAuth
hook. Everything works smoothly when there's an active internet connection, but I'm facing issues when offline.
An error message shows up:
Server Error
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists with different options or config (app/duplicate-app).
I have a feeling that the problem lies in the way I initialize Firebase within my hook. Here is the relevant code snippet:
if (firebaseConfig) {
app = initializeApp(firebaseConfig);
authInstance = getAuth(app);
}
Is there a more graceful way to handle Firebase initialization when there's no internet connection? I want to prevent this duplicate app error from occurring. Any suggestions on how to tackle this issue would be highly appreciated.
I attempted to add a conditional check before initializing the Firebase app to avoid reinitializing it if it already exists. Here's the code I added:
if (!app) {
app = initializeApp(firebaseConfig);
authInstance = getAuth(app);
}
I hoped that this conditional check would ensure that the Firebase app is only initialized if it doesn't exist. My intention was to resolve the "FirebaseError: Firebase App named '[DEFAULT]' already exists with different options or config" issue when the app is offline. However, it seems like the error persists. Any insights on handling Firebase initialization more effectively in offline situations would be welcomed.
const useFireBaseAuth = ({ firebaseConfig }: UseFireBaseAuthProps) => {
const router = useRouter();
const [authUser, setAuthUser] = useState<auth.User | null>(null);
const [loading, setLoading] = useState(true);
let app: any;
let authInstance: auth.Auth;
const toast = useToast();
if (firebaseConfig) {
app = initializeApp(firebaseConfig);
authInstance = getAuth(app);
}
const handleLogout = () => {
signOut(authInstance).then((res) => {
router.push("/");
});
};
const authStateChangeHandler = (authState: any) => {
if (!authState) {
setAuthUser(null);
setLoading(false);
} else {
setAuthUser(authState);
setLoading(false);
}
};
useEffect(() => {
const unsubscribe = authInstance.onAuthStateChanged(authStateChangeHandler);
return () => {
unsubscribe();
};
}, []);
return {
user: authUser,
loading,
logOut: handleLogout,
};
};