use-http icon indicating copy to clipboard operation
use-http copied to clipboard

Interceptors aren't chained

Open veloware opened this issue 3 years ago • 8 comments

Describe the bug Interceptors aren't chained, in that global interceptors at the provider level, are overridden if an interceptor is introduced at the useFetch() hook level

There does seem to be a work around, at the hook level -

request: async ({ options }) => {
        globalOptions.interceptors?.request?.({ options });
        ...

However, that could easily be forgotten on a case per case basis, and is no different that just housing the 'global' interceptor code in a standard function, and just invoking that, which defeats the purpose of a global 'interceptor'

⚠️ Make a Codesandbox ⚠️ Please do this to easily reproduce the bug.

To Reproduce

  • introduce a request interceptor at the provider level, to say, add a request correlation-id header
  • introduce a request interceptor at the hook usage level, to say, add another request header
  • When running the hook, the provider level request interceptor does not run.

Expected behavior Both should run, probably the global first, then the more specific interceptor at the hook level second

veloware avatar Jun 20 '22 12:06 veloware

@veloware I came across the same problem and solved very similar approach as you mentioned.
I think you can create a pull request with this change so it can be reviewed ?

krishnasaga avatar Dec 03 '22 20:12 krishnasaga

@veloware how can you access the globalOptions?

alon-green avatar Dec 06 '22 08:12 alon-green

@alon-green there is a 2nd arg you can pass to useFetch as a callback, its the first arg of that callback, e.g. -

useFetch(url, (globalOptions) => ({
   ...
    interceptors: {
      request: async ({ options }) => {
        globalOptions.interceptors?.request?.({ options });
        ...

veloware avatar Dec 06 '22 09:12 veloware

@veloware thanks for the answer, but I already pass options in the useFetch, in nested hook, I need access to the option of the provider

alon-green avatar Dec 06 '22 09:12 alon-green

in the case above though, the globalOptions is not passed to the callback, it's provided by the callback. Those will be the options that were set at the <Provider options={xxx}> level

veloware avatar Dec 06 '22 09:12 veloware

But I can't access the provider, can't I take it from the context or something?

alon-green avatar Dec 06 '22 09:12 alon-green

@veloware Let me try to create a CodesandBox of this

krishnasaga avatar Dec 07 '22 20:12 krishnasaga

@alon-green here is the CodeSandbox https://codesandbox.io/s/usefetch-use-http-todo-list-app-managed-state-forked-x1ru0p?file=/src/index.js. If this code sandbox is clarifying solution to your problem or still, it is a problem. now you can modify the code sandbox to help us to understand better. hopefully we can solve it.

@veloware

krishnasaga avatar Dec 07 '22 20:12 krishnasaga