CSFrequency / react-firebase-hooks

React Hooks for Firebase.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useDocumentData returns undefined on first render until forced browser refresh returns data

BinDohry opened this issue · comments

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.

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.

@Yey007 I fixed my issue by moving any real-time listeners from React Context to the components that need the data. As for dataOnce methods, they work fine for me in either context or within components.

I'm glad you fixed your issue. Here is my minimal reproducible example. The document is stuck in the loading state forever.

const db = getFirestore();

const Test: React.FC = () => {
  const docRef = doc(db, 'classes', 'Ltc50dzunHy7TWVoSR9T');

  const [course, courseLoading, courseError] = useDocumentDataOnce(docRef);

  if (courseLoading) {
    console.log('loading');
    return <LoadingPage></LoadingPage>;
  }

  if (courseError) {
    console.log('error');
    return <ErrorPage></ErrorPage>;
  }

  console.log(':)');
  return <div>:)</div>;
};

"loading" is logged, and then nothing. Perpetual loading. The id is a valid id and the reference exists. I know because everything loads fine after I reload the module by making a change. Even more bizarre is the fact that we don't face this issue in the live production build.

Edit: removed useParam in case there was any doubt.

@Yey007 Try this:

  1. https://stackoverflow.com/a/64510846/6858112
  2. https://bobbyhadz.com/blog/react-listen-to-state-change
import { useEffect } from 'react';

const db = getFirestore();

const Test: React.FC = () => {

  const docRef = doc(db, 'classes', 'Ltc50dzunHy7TWVoSR9T');

  const [course, courseLoading, courseError] = useDocumentDataOnce(docRef);


useEffect(() => {
console.log(courseLoading)
console.log(courseError)
console.log(course)

}, [courseLoading, courseError, course])

  return (
  {courseloading && <LoadingPage></LoadingPage> }
  {courseError && <ErrorPage></ErrorPage>}
  {course && <div>:)</div>}
  );

};

Hope that helps :)

Edit: Fixed URL's

@BinDohry It's the same deal, unfortunately.

This is probably the same problem as the one mentioned in this other issue: #231

I assume that this is related to new features in React 18, so the React version in react-firebase-hooks is going to have to be upgraded to 18, but don't know who are the people that maintain the repo 🤷🏻‍♂️

@marduzca In my initial code example, I was using React 17 and was still having the issue.

@BinDohry
Interesting, that I didn't expect. Not sure what the problem is then

I am also encountering this issue using React v18. I've switched from useDocumentDataOnce to useDocumentData as a temporary workaround.

@Garee Yeah, that's the workaround I found as well. I'm not exactly sure why this is happening, but I unfortunately don't have the time to investigate. I wish I could.

commented

Currently suffering the same problem. It's working fine in production but not on development. I'm scared that updating my production app will result a huge break.

commented

I have now fixed this. I had to delete node_modules as well as my .next folder and reinstall

I'm also having the same issue. As mentioned above, using useDocumentData works as a temporary workaround.

Here are my relevant dependencies:

  "firebase": "^9.9.4",
  "next": "12.3.0",
  "react": "18.2.0",
  "react-dom": "18.2.0",
  "react-firebase-hooks": "^5.0.3",

@lewisd1996 in the same situation. Unfortunately reinstalling did not work for me. Tried deleting the lock file and node modules to no avail.

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?

Tested again and it seems to work fine. Thanks for the update!

Thanks @pythonicode, I will close this issue, but if anybody else is still struggling, please let me know and I can look into it further!

@chrisbianca Thank you so much, the fix works!