1

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?

2 Answers 2

6

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...>
   )
}
Sign up to request clarification or add additional context in comments.

1 Comment

Duh. Thank you. Staring at this for too long I think! Leaving it here in case anyone else has a similar issue.
2

as an alternative to the accepted answer, you could pass down the refetch method returned from useQuery:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.