Nick
Nick

Reputation: 420

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

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

Upvotes: 7

Views: 8943

Answers (1)

christiandrey
christiandrey

Reputation: 491

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.

Upvotes: 18

Related Questions