A thin fetch
wrapper with useful defaults. Inspired by got.
npm install use-fetch
or
yarn add use-fetch
<script src="https://unpkg.com/use-fetch@latest/dist/index.js"></script>
<script src="https://unpkg.com/use-fetch@latest/dist/index.min.js"></script>
You can access package through window.usefetch
.
import usefetch from 'use-fetch';
usefetch('/messages', { json: true })
.then(response => {
console.log(response.body);
});
Returns a promise for a response
object with a body
property.
Type: string
object
The URL to request as a string or a Request object.
Type: object
Any of the fetch init options.
Type: object
Default: {}
Request headers.
Type: boolean
Default: false
If set to true
and content-type
header is not set, it will be set to application/json
.
Takes a response stream and reads it to completion through the response.json()
. The result is parsed as JSON and saved to response.body
. Sets the accept
header to application/json
.
body
must be a plain object or array and will be stringified.
Type: number
object
Default:
- retries: 2
- methods:
GET
,PUT
,HEAD
,DELETE
,OPTIONS
,TRACE
- statusCodes:
408
,413
,429
,500
,502
,503
,504
The numeric value sets the retries
amount. The object represetns retries
, methods
, statusCodes
fields.
It makes another request for listed methods and status codes in case of timeout or response was not successful (status in range 200-299).
Type: number
Default: 0
Milliseconds to wait for the server to respond before aborting request with error. By Default there's no timeout.
To create fetch
with your own preset use the createFetch
function. By default it is initialized as in the example below.
import { createFetch } from 'use-fetch';
const usefetch = createFetch({
// spec
credentials: 'same-origin',
redirect: 'follow',
// custom
json: false,
redirect: 'follow',
throwHttpErrors: true,
timeout: 0,
});
export default usefetch;
Each error contains (if available) status
, statusText
, url
and response
properties to make debugging easier.
When server response code is not 2xx.
When json
option is enabled, server response code is 2xx, and response.json()
fails.
When server didn't respond within specified timeout.
To use the library in browsers, that doesn't have fetch (see support here), you may want to add a polyfill. Check the unfetch project.
The contents of src folder written in es5 syntax — saves times on transpilers setup, cause you don't need any.
yarn bundle
— create standalone browser bundleyarn check-es5
— checks if it's a valid es5 syntaxyarn lint --fix
— lint the code and fix stylistic issuesyarn test
— run tests in google chrome
- Add support of AbortController with request cancellation.
- Read response stream as text by default.
- Add support of the Request object.
The MIT License