skip to Main Content

I know the regular refetching of the data in useQuery

const fetchData = async()=>{...}

// it starts fetching data from backend with this line of code
const {status, data, error, refetch } = useQuery(
myKey, 
fetchData(),
{
  enabled: false,
}
);
const onClick = () => { refetch() }

I know this refetches data (makes an API call) everytime the onClick function is called. I only want the API call to be made if the data is stale like the when the useQuery function is called. Is there a way to do that ?

2

Answers


  1. Check if the data is stale and refetch accordingly.

    const ComponentX = ()=>{
    
        const {status, data, error ,isStale, refetch } = useQuery(
          key, 
          fetcherFn,
          {
            staleTime: 10 * 1000,
            enabled: false,
          }
        )
    
        const onClick = ()=>{
            if (isStale) refetch() 
        }
    
    }
    
    
    Login or Signup to reply.
  2. Its like a google search, everytime a new key is entered, an API call is made to fetch the results and update them on screen

    Judging from this, you are likely looking for lazy queries. It’s important that you make the entered search string part of your queryKey.

    const [search, setSearch] = React.useState('')
    
    const { data } = useQuery({
      queryKey: ['query', search],
      queryFn: () => fetchQuery(search),
      enabled: !!search
    })
    

    With this, you don’t need refetch() at all.

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