Home > other >  Trigger a query refresh (invalidate?) from onClick handler
Trigger a query refresh (invalidate?) from onClick handler

Time:12-16

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?

CodePudding user response:

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...>
   )
}
  • Related