Skip to content

Instantly share code, notes, and snippets.

@HKhademian
Created April 21, 2021 12:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save HKhademian/0bb47b019e874411c0a2be9292b0487d to your computer and use it in GitHub Desktop.
import {useEffect, useState} from "preact/hooks";
export const useFetch = (
{
url, // request url
parse = 'json', // default body parser
placeholder = undefined, // when error|loading return this as data
key = undefined, // to track different changes (latter to cache)
...options // fetch() options like methods , ...
} = {}
) => {
const [state, setState] = useState({
isError: false, isLoading: false, isReady: false,
data: placeholder, error: undefined,
});
useEffect(() => {
const controller = new AbortController(); // use to cancel previous requests
const opts = Object.assign({signal: controller.signal}, options); // U can change default signal to whatever you want
fetch(url, opts)
.then(async response => {
const data =
parse === 'json' ? await response.json() :
parse === 'text' ? await response.text() :
parse === 'arrayBuffer' ? await response.arrayBuffer() :
parse === 'blob' ? await response.blob() :
parse === 'formData' ? await response.formData() :
response;
setState({
isError: false, isLoading: false, isReady: true,
data, error: undefined,
});
}).catch(err => {
setState({
isError: true, isLoading: false, isReady: false,
data: placeholder, error: err,
});
});
setState({
isError: false, isLoading: true, isReady: false,
data: placeholder, error: undefined,
});
return () => controller.abort(); // cancels fetch request on exit
}, [url, parse, options, key]); // auto refresh on url|options|parse|key
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment