use-fetch-factory generates a [hook] that provides the state and settled response of a fetch.
It is 597 bytes (351 gzipped).
Installation
npm install @jsxtools/use-fetch-factory
Usage
import { useEffect, useRef, useState } from 'react';
import useFetchFactory from '@jsxtools/use-fetch-factory';
const useFetch = useFetchFactory({ useEffect, useRef, useState });
function Component () {
// the `state` is "pending", "fulfilled", or "rejected"
// the `response` is the response from the fetch
const [ state, response ] = useFetch('https://httpbin.org/get');
return state === 'pending'
? 'Loading'
: JSON.stringify(settledValue);
}
Abort
const [ state, response, abort ] = useFetch('https://httpbin.org/get');
// abort the fetch
abort();
Timeout
// abort the fetch after 2000ms
const [ state, response ] = useFetch('https://httpbin.org/get', {
timeout: 2000
});