CSFrequency / react-firebase-hooks

React Hooks for Firebase.
Apache License 2.0
3.55k stars 304 forks source link

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

Closed BinDohry closed 1 year ago

BinDohry commented 2 years ago
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.

Yey007 commented 1 year ago

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.

BinDohry commented 1 year ago

@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.

Yey007 commented 1 year ago

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.

BinDohry commented 1 year ago

@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

Yey007 commented 1 year ago

@BinDohry It's the same deal, unfortunately.

marduzca commented 1 year ago

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 🤷🏻‍♂️

BinDohry commented 1 year ago

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

marduzca commented 1 year ago

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

Garee commented 1 year ago

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

Yey007 commented 1 year ago

@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.

lewisd1996 commented 1 year ago

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.

lewisd1996 commented 1 year ago

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

jamesdarabi commented 1 year ago

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",
Yey007 commented 1 year ago

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

jdgamble555 commented 1 year ago

It is returning undefined here

https://github.com/CSFrequency/react-firebase-hooks/blob/master/firestore/useDocument.ts#L98

and same thing with collections

https://github.com/CSFrequency/react-firebase-hooks/blob/master/firestore/useCollection.ts#L80

Someone needs to debug this perhaps and submit a pull request.

J

chrisbianca commented 1 year ago

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?

pythonicode commented 1 year ago

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

chrisbianca commented 1 year ago

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!

Yey007 commented 1 year ago

@chrisbianca Thank you so much, the fix works!