2

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?

1 Answer 1

2

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 (...);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good idea! This is what I'll probably do if I can't find a way to inject the function directly. Will mark as answer if I can't find another way. Thanks for the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.