简体   繁体   中英

How to refetch queries from sibling component with react-query

I was wondering how to refetch a query from another sibling component with react-query.

Lets say I have Component A

 import {useQuery} from "react-query";

 function ComponentA(){

    const getData = async () => data //returns api data

    const {data, refetch} = useQuery(["queryA"], async () => await getData())

    return(

         <div>
           {data}
         </div>

   )}

And in Component B

 import {useQuery, QueryClient} from "react-query";

 function ComponentB(){

    const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            staleTime: Infinity,
        },
    },
})

const refreshQueryFromComponentA = async () => {
     await queryClient.refetchQueries(["queryA"], { active: true })
}

    return(

         <div>
           <button onClick={refreshQueryFromComponentA}/>
         </div>

   )}

And in Page.js

 import ComponentA from "./componentA";
 import ComponentB from "./componentB";

 function Page(){

    return(

         <div>
           <ComponentA/>
           <ComponentB/>
         </div>

   )}

When I call the refreshQueryFromComponentA function in ComponentB I do not see the query refresh in ComponentA or a new call to the backend in the network tab. I also use the correct query-key but I am only able to refetch the query in ComponentA with the refetch() function which comes from the useQuery function.

I think it's possible what I'm trying to do, since react-query uses context and should be available throughout the whole application. But maybe I'm using the wrong method or misinterpreted it.

Thanks in advance everyone!

There needs to be one QueryClient at the top of your app. The QueryClient holds the queryCache, which stores your data. If you create a new one in componentB, it won't share anything with componentA. Also, make sure to add it to the QueryClientProvider and retrieve it via useQueryClient() . The client also needs to be stable, so don't create a new one each render. This is from the first page of the docs:

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
2 
3 const queryClient = new QueryClient()
4 
5 export default function App() {
6   return (
7     <QueryClientProvider client={queryClient}>
8       <Example />
9     </QueryClientProvider>
10   )
11 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM