#How to trigger the OnRequest methods when performing a JS fetch API call?

6 messages · Page 1 of 1 (latest)

mighty ore
#

Good afternoon, is there any way to trigger the OnRequest middleware function when API calls are performed using the Javascript functions (i.e. fetch) in QWIK? I would like to have this behavior because i want to show a spinner when the HTTP request starts and hide that when that is completed. I am performing the HTTP request inside a useVisibleTask method of a standard qwik component.

Best regards,
Xhoi

compact ruin
#

you are describing useResource$ is a better way if your fetch is "almost standard"

#

the spinner will go inside "onPending"

mighty ore
#

That's good, but I think that useResource needed to be put in each component you use it. Instead, i needed a centralized way to handle the spinner on/off mechanism, like in an Angular interceptor. Is there any way to get an interceptor which is fired at each http request to a backend API application?

blazing jolt
#

You can wrap globalThis.fetch in a useVisibleTask in a spinner component. When the fetch starts/stops, inc/dec a counter, and show the spinner when the counter != 0

The only problem is knowing when fetch is done, which you can only really do if you wrap the body of the result. https://chatgpt.com/share/67050cbf-5eac-8012-9c85-78ffb6090928