Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useDocument causes infinite loops #325

Open
ItsAnoch opened this issue Jul 30, 2024 · 0 comments
Open

useDocument causes infinite loops #325

ItsAnoch opened this issue Jul 30, 2024 · 0 comments

Comments

@ItsAnoch
Copy link

When using useEffect and useDocument infinite loops.

This is a custom hook I have to have up to date use data.

export function useUserData(): UseUserDataReturn {
  const { data: session, status } = useSession();

  const documentRef = useCallback(() => {
    return session?.user?.id ? doc(db, 'users', session.user.id) : null;
  }, [session?.user?.id]);

  const options = useMemo(() => ({
    snapshotListenOptions: { includeMetadataChanges: true },
  }), []);

  const [value, loading, error] = useDocument(documentRef(), options);

  const userData = value?.data() as User | null;

  return {
    session,
    status,
    userData,
    loading,
    error
  };
}

If I create a separate state and use useEffect to update that state when userData changes it causes an infinite loop. Here's an example.

const { userData } =  useUserData();
const [ cart, setCart ] = useState<string[]>([]);

useEffect(() => {
   if (!userData) return;
   setCart( Object.keys( userData.cart ) );
}, [ userData ]);

Am I doing something wrong? Is there a way to fix this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant