https://github.com/dankreiger/puppy-fetch
a small wrapper for the fetch api that automatically aborts unneeded requests
https://github.com/dankreiger/puppy-fetch
abortcontroller fetch
Last synced: 11 months ago
JSON representation
a small wrapper for the fetch api that automatically aborts unneeded requests
- Host: GitHub
- URL: https://github.com/dankreiger/puppy-fetch
- Owner: dankreiger
- Created: 2020-01-01T19:19:58.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-12-15T14:52:47.000Z (about 2 years ago)
- Last Synced: 2025-03-03T15:49:41.622Z (12 months ago)
- Topics: abortcontroller, fetch
- Language: TypeScript
- Homepage:
- Size: 1.3 MB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 12
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
### Puppy Fetch
A small wrapper for the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) that uses the [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) interface to cancel in-flight fetch requests.
Using `puppy-fetch` helps by making repeated `fetch` calls abortable by default. This is especially helpful for speeding up the UX for users with a slower internet connection.
[](https://travis-ci.org/dankreiger/puppy-fetch)
[](https://codesandbox.io/s/objective-varahamihira-hc7py?fontsize=14&hidenavigation=1&theme=dark)
### Install
```sh
npm install puppy-fetch
```
or
```sh
yarn add puppy-fetch
```
### Usage
1. import `puppyFetch`
```js
import puppyFetch from 'puppy-fetch';
```
2. Give `puppyFetch` a unique identifier, and then use it just like you would use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
```js
const some_unique_string = 'some_unique_string';
const another_unique_string = 'another_unique_string';
// GET EXAMPLE
puppyFetch(
some_unique_string,
'https://jsonplaceholder.typicode.com/todos/1'
);
// POST EXAMPLE (note, when aborting, you should not mutate information on the server)
puppyFetch(another_unique_string, 'https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
});
```
Requests with the same unique identifier will be automatically aborted.
---
You can polyfill older browsers by running:
```sh
npm install --save abortcontroller-polyfill
```
and then importing the polyfill above your `puppy-fetch` import:
```js
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only';
import puppyFetch from 'puppy-fetch';
```
See https://www.npmjs.com/package/abortcontroller-polyfill for more information.
---
More info:
Aborting an instance of a finished request does nothing, and therefore is [fine to do](https://developers.google.com/web/updates/2017/09/abortable-fetch).