Skip to content

useDocument causes infinite loops #325

Description

@anochj

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions