Recommand · June 2, 2021 0

refetch with different data react query

I try to Refetch every button is click and get a new data

const {refetch,data,isLoading} = useQuery(
    "getkurs",() =>fetch( `https://free.currconv.com/api/v7/convert? 
      q=${selected.country.currencyId}_IDR&compact=ultra&apiKey=${process.env.COUNTRY_API}`).then((res) => 
    res.json()),{ enabled: false, refetchOnWindowFocus: false }
  );

<button onclick={()=>refetch()}>click</button>

It’s only work once but in second and etc it’s not working , can someone help me ?

You can pass parameters to the query keys, because React Query will automatically trigger a refetch when the value in the query keys changes.

const [selectedCurrencyId, setSelectedCurrencyId] = React.useState()

const {data,isLoading} = useQuery(['getkurs', selectedCurrencyId], () => fetch(....))

so if you want to refetch, you can call setSelectedCurrencyId with the currency value.