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

Calling React hook in a function

Is there a chance I can run a query with a useQuery hook only if the button is clicked?

const handleClick = () => {
  const [, { data }]  = useLazyQuery(GET_ORDER_INVOICE, {
    variables: { order_Id: orderNumber }
  });

  return '';
};

<Button
  priority={ButtonPriority.SECONDARY}
  onClick={ () => {
    handleClick();
  } }
/>

However, this breaks with the React Hook "useLazyQuery" is called in function "handleClick" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. Is there a chance I can bind calling a query to a button click?

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

>Solution :

You need to call useLazyQuery in the body of your component. It will then return to you a function that you can call in handleClick:

const Example = () => {
  const [executeQuery, { data }] = useLazyQuery(GET_ORDER_INVOICE);

  const handleClick = () => {
    executeQuery({
      variables: { order_Id: orderNumber }
    })
  }

  // ...
  <Button
    priority={ButtonPriority.SECONDARY}
    onClick={handleClick}
  />
}
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