0

I'm trying to work out how to change the behaviour of an existing hook, specifically the useAsync hook provided by the react-async library. It's a hook for making async requests to an API.

I'd like to change the behaviour of the hook in a number of ways, such as checking for an auth token before running the query and putting a call on hold if the token isn't found, and dealing with errors in a consistent way every time I maka a call.

So, can I just create a new hook - useWrappedAsync which makes use of a call to useAsync under the hood and exposes all of the returned values from useAsync back to the callee of useWrappedAsync? Something like this.

import{ useAsync } from "react-async";

function useWrappedAsync(options) {

  const {specialOption1, specialOption2, ...asyncOptions} = options

  ... code here for checking token in redux etc.
  
  const internalAsync = useAsync(asyncOptions)

  const wrappedAsync = {newParam1, newParam2, ...internalAsync}

  return wrappedAsync

}

So, I'm able to add new params when calling it but I remove these before using react-async. I'm also able to expose new paramaters to the value returned before adding in all the ones from the useAsync hook.

I'm not entirely sure I've got this right. I "think" it should work but I can't find any examples of it. Is this a common pattern? Is there a better more obvious way? and would there be any problems with calling the wrapped hook twice for example?

Any help would be very appreciated.

jonhobbs
  • 21,469
  • 23
  • 94
  • 144
  • 1
    This is exactly what custom hooks are for. Encapsulating common behavior from components or adding behavior to another hook. For instance useState is commonly used in custom hooks https://reactjs.org/docs/hooks-custom.html – windowsill Nov 11 '20 at 23:10

0 Answers0