Boris Lebedev
Boris Lebedev

Reputation: 143

How to return a request function from useQuery in react-query

I have a React hook that returns a request functions that call an API

It has the following code:

export const useGetFakeData = () => {
  const returnFakeData = () =>
    fetch('https://fake-domain.com').then(data => console.log('Data arrived: ', data))

  return returnFakeData
}

And then I use this hook in component something like this

const getFakeData = useGetFakeData()

useEffect(() => getFakeData(), [getFakeData])

How to achieve this effect in react-query when we need to return a request function from custom hook?

Thanks for any advice!

Upvotes: 0

Views: 4713

Answers (3)

Boris Lebedev
Boris Lebedev

Reputation: 143

Digging in docs, I find out that React-Query in useQuery hook provide a refetch() function.

In my case, I just set property enabled to false (just so that the function when mount is not called automatically), and just return a request-function like this

export const useGetFakeData = () => {
  const { refetch } = useQuery<void, Error, any>({
    queryFn: () =>
      fetch('https://fake-domain.com').then(data => console.log('Data arrived: ', data)),
    queryKey: 'fake-data',
    enabled: false,
  })

  return refetch
}

Upvotes: 1

TkDodo
TkDodo

Reputation: 28843

I think you are just looking for the standard react-query behaviour, which is to fire off a request when the component mounts (unless you disable the query). In your example, that would just be:

export const useGetFakeData = () =>
  useQuery('fakeData', () => fetch('https://fake-domain.com'))
}


const { data } = useGetFakeData()

Please be advised that this is just a bare minimal example:

Upvotes: 0

NearHuscarl
NearHuscarl

Reputation: 81410

You can use useMutation hook if you want to request the data using the imperative way. The data returned from the hook is the latest resolved value of the mutation call:

const [mutate, { data, error }] = useMutation(handlefunction);

useEffect(() => {
  mutate(...);
}, []);

Upvotes: 0

Related Questions