Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.js – call useDocument hook conditionally

I have the following code in React:

export const useData= (previewMode: boolean) => {
  if (previewMode) {
    let [value_, loading, error]: any = useDocument(
      doc(getFirestore(app), "settings", "content"),
      {
        snapshotListenOptions: { includeMetadataChanges: true },
      },
    );

    const value: any =
      value_?.data() === undefined ? { data: contentFile } : value_.data();

    return { data: value, loading: loading };
  }
  return {data: contentFile, loading: false};
};

contentFile is a static JSON file that

The thing is I keep getting the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

src\lib\use-data.tsx
  Line 11:41:  React Hook "useDocument" is called conditionally. React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks

Now I know the rules of react-hooks, but the problem is that I need a condition, without it, the useDocument hook will be always called and we will query the firestore and I don’t want that.

I only want to load the document if the previewMode is on, is that possible?

This is how I use this hook:
const { value, data } = useData(previewMode);

Thanks in advance

>Solution :

You can’t place a hook into a condition. They must be declared top level in the component, because React indexes them based on their order, then you use the declared result inside the condition.

In your case:

export const useData = (previewMode: boolean) => {
  const document = useDocument(
    doc(getFirestore(app), "settings", "content"),
    {
      snapshotListenOptions: { includeMetadataChanges: true },
    }
  );

  if (previewMode) {
    let [value_, loading, error]: any = document;
  }
  /* rest of component */
}

document is now declared regardless of the condition, and React can track it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading