💪 Using Hooks
Hooks allow you to hook into the request lifecycle.
Looking for interceptors?
You want to hook into some lifecycle, great, they're called hooks!
Hooks are a powerful feature that allow you to hook into the request lifecycle in order to intercept it and modify the request or response. Hooks can be used to implement features such as authentication, logging, custom caching, and more.
This is a common pattern in fetch libraries and so you can use it in kinda similar use cases.
Explanation
- Each hook is set when setting up your instance
- Each hook's value is a callback which has a context in it's argument.
- The context has the request, result and config of the instance at runtime.
- You can modify and return your modified config, request or result respectively.
- Basically, you return the modified context or a partial of it you have modified.
- The modification is what will be applied to the request or response accordingly.
The context object has the following properties:
A) request: The request object that is being sent.
This includes url
, method
and options
for that request.
B) result: The result object that is being received.
This is Z-fetch result including data
, error
, response
and other properties.
C) config: The configuration object that is being used.
-> Tip: you can always just pick only what you want to modify, and then return that after modifying it.
Request Hooks
Request hooks allow you to modify the request before it's sent:
Response Hooks
Response hooks allow you to modify the response before it's returned:
Combining Request and Response Hooks
You can use both request and response hooks together:
Real-World Example: Authentication and Logging
With these powerful hooks, you can implement complex request/response processing, authentication flows, logging, error handling, and data transformation in a clean and reusable way.
Any more hooks you think would be useful? Feel free to suggest them!