skip to Main Content

Hi I was wondering how do i keep polling an api until a condition is met with react query.
I have a query function that makes a call to the api and returns the response data so for example it it will return an object like this

{
name: string
age: number
job: string
}

I want to be to keep polling until I get a specific name for example.

  const fetchQuery = useQuery({
    queryKey: ['fetchQuery'],
    queryFn: fetchApi,
    enabled: false,
  });

I see the refetchInterval option but unsure how to access the data to be able to do something like

refetchInterval(query){
 if(query.name === 'my-name'){return false;}
 return 3000;
}

}

2

Answers


  1. I think useInfiniteQuery might be what you’re looking for?

    Login or Signup to reply.
  2. You can use the queryClient and invalidate the query until your condition is met.

    Eample

    import queryClient from 'your-react-query-config'
    
    const queryHook = () => {
        const { data } = useQuery({
            queryKey: ['fetchQuery'],
            queryFn: fetchApi,
        });
    
        if (data.name !== 'my-name') {
            // Condition is not met, let's re-fetch the query
            queryClient.invalidateQueries(['fetchQuery'])
        }
    
        return { data } 
    }
    

    https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientinvalidatequeries

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search