React - Error: Rendered more hooks than during the previous render with Custom Hook

Viewed 404

I have a component in which I'm calling my custom hook.

The custom hook looks like this:

import { useQuery } from 'react-apollo';

export function useSubscription() {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  if (loading) return false
  if (error) return null

  return data
}

And then the component I'm using it in that causes the error is:

export default function Form(props) {
  const router = useRouter();

  let theSub = useSubscription();
  if (theSub === false) {
    return (
      <Spinner />
    )
  } // else I'll have the data after this point so can use it.

  useEffect(() => {

    if (!isDeleted && Object.keys(router.query).length !== 0 && router.query.constructor === Object) {
      setNewForm(false);

      const fetchData = async () => {
        // Axios to fetch data
      };

      fetchData();
    }

  }, [router.query]);

  // Form Base States
  const [newForm, setNewForm] = useState(true);
  const [activeToast, setActiveToast] = useState(false);


  // Form Change Methods
  const handleUrlChange = useCallback((value) => setUrl(value), []);

  const handleSubmit = useCallback(async (_event) => {
    // Submit Form Code
  }, [url, selectedDuration, included, excluded]);


  return (
    <Frame>
      My FORM
    </Frame>

  )


}

Any ideas?

1 Answers

You can use useEffect for calling hook at the first time of rendering component.

export default function Form(props) {
  const router = useRouter();
  const [theSub, setTheSub] = useState(null);
  useEffect(() => { setTheSub(useSubscription()); }, []);
  
  if (theSub === false) {
    return (
      <Spinner />
    )
  } // else I'll have the data after this point so can use it.

  // I have some other states being set and used related to the form e.g:
  // const [whole, setWhole] = useState(true);

  return (... The form ...)
Related