Function: fetch()
fetch<
T,TOptions,TAs,TReturn>(url,options?):IPromise_Fetch<TReturn>
Defined in: packages/fetch/src/index.ts:161
fetch A fetch() replacement that simplifies data fetching with automatic JSON parsing, request timeouts, retries, and handy interceptors that also work as transformers. It also includes deferred and throttled request capabilities for complex asynchronous control flows.
Will reject promise if response status code is not 2xx (200 <= status < 300).
Method Specific Functions
While fetch() provides access to all HTTP request methods by specifying it in options (eg: { method: 'get' }), for ease of use you can also use the following:
fetch.delete(...)fetch.get(...)fetch.head(...)fetch.options(...)fetch.patch(...)fetch.post(...)fetch.put(...)
Deferred variants: To debounce/throttle requests.
fetch.delete.deferred(...)fetch.get.deferred(...)fetch.head.deferred(...)fetch.options.deferred(...)fetch.patch.deferred(...)fetch.post.deferred(...)fetch.put.deferred(...)
Type Parameters
T
T = unknown
The type of the value that the fetch resolves to.
TOptions
TOptions extends FetchOptions = FetchOptions
TAs
TAs extends FetchAs = TOptions["as"] extends FetchAs ? any[any] : response
TReturn
TReturn = FetchResult<T>[TAs]
Return value type.
If T is not specified defaults to the following based on the value of options.as:
- FetchAs.arrayBuffer:
ArrayBuffer - FetchAs.blob:
Blob - FetchAs.bytes:
Uint8Array<ArrayBuffer> - FetchAs.formData:
FormData - FetchAs.json:
unknown - FetchAs.text:
string - FetchAs.response:
Response
Parameters
url
URL | RequestInfo
options?
Omit<RequestInit, "body"> & object & Omit<Partial<RetryOptions>, "retry" | "retryIf"> & object & TimeoutOptions<[]> & TOptions = ...
(optional) Standard fetch options extended with FetchCustomOptions
Returns
IPromise_Fetch<TReturn>
Examples
Drop-in replacement for built-in fetch
import fetch from '@superutils/fetch'
fetch('[DUMMYJSON-DOT-COM]/products/1')
.then(response => response.json())
.then(console.log, console.error)Method specific function with JSON parsing by default
import fetch from '@superutils/fetch'
// no need for `response.json()` or "result.data.data" drilling
fetch.get('[DUMMYJSON-DOT-COM]/products/1')
.then(product => console.log(product))
fetch.post('[DUMMYJSON-DOT-COM]/products/add', { title: 'Product title' })
.then(product => console.log(product))Set default options
Options' default values (excluding as and method) can be configured to be EFFECTIVE GLOBALLY.
import fetch from '@superutils/fetch'
const { defaults, errorMsgs, interceptors } = fetch
// set default request timeout duration in milliseconds
defaults.timeout = 40_000
// default headers
defaults.headers = { 'content-type': 'text/plain' }
// override error messages
errorMsgs.invalidUrl = 'URL is not valid'
errorMsgs.timedout = 'Request took longer than expected'
// add an interceptor to log all request failures.
const fetchLogger = (fetchErr, url, options) => console.log('Fetch error log', fetchErr)
interceptors.error.push(fetchLogger)
// add an interceptor to conditionally include header before making requests
interceptors.request.push((url, options) => {
// ignore login requests
if (`${url}`.includes('/login')) return
options.headers.set('x-auth-token', 'my-auth-token')
})