Home > Net >  How to resend a query with useQuery based on different state?
How to resend a query with useQuery based on different state?

Time:03-11

So my example:

const Component = () => {
  const [param, setParam] = useState('defaul')
  const { isLoading, isError, data } = useQuery('data', () => fetch(`https://test.com?param=${param}`)

  ....
}

For example, I will change param state in someplace and I want to fetch a date with this updated param. I want to resend the API call each time the param state is changing. How can I achieve this?

P.S. Im using React Query lib

CodePudding user response:

Including your param in the queryKey in the useQuery declaration should automatically refetch the data when the param changes. See modified example below:

const Component = () => {
  const [param, setParam] = useState('defaul')
  const { isLoading, isError, data } = useQuery(['data', param], () => fetch(`https://test.com?param=${param}`)

  ....
}

For more details, see here.

  • Related