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

Trigger a query refresh (invalidate?) from onClick handler

New to react-query. Have a pretty table with a manual refresh button. The parent that owns the table and button row owns the query, and I’m passing a "reload" function down through props, which the onClick (a few levels down) executes:

const MyComponent = () => {
   
   var qKey = ['xyz', foo, bar];
   
   const reload = () => {
        useQueryClient().invalidateQueries(qKey)
   }

   const {isLoading, error, data, isFetching} = useQuery(qKey, async () => {
      /* stuff */
      return response.json()
    }, {keepPreviousData: true});

   return (
      <ActionsBar onRefresh={reload} onClear={foo} onSearch={bar}/>
      <Other stuff...>
   )
}

const ActionBar = (props) => {
   const {onRefresh, onClear, onSearch} = props;

   return (
      <Button onClick={ () => onRefresh()}>Refresh</Button>
      /* other stuff */

Getting an error that "reload" is calling a hook but is not a React function component or a customer React hook function.

I suspect this is a useEffect issue but not sure how that fits into the above scenario?

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 :

put const queryClient = useQueryClient(); under MyComponent function,

and call queryClient inside the reload function.

const MyComponent = () => {
   const queryClient = useQueryClient()
   var qKey = ['xyz', foo, bar];
   
   const reload = () => {
        queryClient.invalidateQueries(qKey)
   }

   const {isLoading, error, data, isFetching} = useQuery(qKey, async () => {
      /* stuff */
      return response.json()
    }, {keepPreviousData: true});

   return (
      <ActionsBar onRefresh={reload} onClear={foo} onSearch={bar}/>
      <Other stuff...>
   )
}
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