react-firebase-hooks: useDocumentData returns undefined on first render until forced browser refresh returns data
import { doc } from 'firebase/firestore';
import { createContext, useEffect, useState } from 'react';
import { auth, db } from '../firebase/firebase-config';
import {
useDocumentData,
useDocumentDataOnce,
} from 'react-firebase-hooks/firestore';
import { useAuthState } from 'react-firebase-hooks/auth';
const userAuthContext = createContext({});
const UserAuthContextProvider = ({ children }: any) => {
const [authUser, loadingAuthUser, errorAuthUser] = useAuthState(auth);
const [authUserDocRef, setAuthUserDocRef]: any = useState();
const [userData, loading, error, snapshot, reload] =
useDocumentDataOnce(authUserDocRef);
const [businessDocRef, setBusinessDocRef]: any = useState();
const [
businessData,
loadingBusinessData,
errorBusinessData,
snapshotBusinessData,
] = useDocumentData(businessDocRef);
useEffect(() => {
if (authUser) {
setAuthUserDocRef(doc(db, 'users', authUser.uid));
}
if (userData) {
setBusinessDocRef(userData.managedBusiness);
}
}, [authUser, userData]);
return (
<userAuthContext.Provider
value={{ authUser, businessData, loadingBusinessData }}
>
{children}
</userAuthContext.Provider>
);
};
export { userAuthContext, UserAuthContextProvider };
businessData returns undefined. I have to manually force refresh the browser for businessData to return the correct value from Firestore.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 19 (2 by maintainers)
Hi everybody, apologies for the delay in investigating this properly. I’ve just given this a try and it appears that some of the changes I’ve made in the newly released v5.1.0 may have inadvertently resolved this issue.
Could I ask you to try v5.1.0 and check whether this has been fixed?
I am also encountering this issue using React v18. I’ve switched from
useDocumentDataOncetouseDocumentDataas a temporary workaround.I’m facing a very similar issue with useDocumentDataOnce. It won’t load, always returning undefined and true for the loading value until I make a change in the code and the module reloads. Very bizarre.