rbhalla
rbhalla

Reputation: 1189

Modifying state in react-query's query function

I have written a wrapper around fetch that lets me handle error states from my API like a 401. When it gets an error, the custom fetch function sets some state using react hooks.

Because I use hooks in the function, I cannot just import it normally. Therefore, I pass this wrapped function around using context.

When I use react-query, I would like to just use this wrapped function in the following way:

function myQuery(key, apiFetch) {
  return apiFetch(...)
}

function MyComponent() {
  useQuery('key', myQuery)
}

In this example, apiFetch is an available argument in the query function.

One option I do have here is to just inline the function like so:

function myQuery(key, apiFetch) {
  return apiFetch(...)
}

function MyComponent() {
  const apiFetch = useApiFetch();
  useQuery('key', (key) => apiFetch(...))
}

However I find this a little messy and would like to keep the query/mutation functions separate if possible.

Does anyone know of an approach I can take to have my apiFetch function be available to me in react-query's functions?

Upvotes: 2

Views: 411

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81280

If you don't want to repeat calling useApiFetch and useQuery hooks in multiple components, you can extract both hooks into another custom hook that integrates react-query with your fetch hook:

function useApiQuery(param) {
  const apiFetch = useApiFetch();
  return useQuery(['key', param], (key) => apiFetch(...))
}

Then use it in your component:

function MyComponent({ param }) {
  const { data, error } = useApiQuery(param);
  
  return (...);
}

Upvotes: 2

Related Questions