react-use-fetch
React hooks for interacting with the fetch API
which includes the ability to add middleware to intercept, modify, cancel, cache, or
analyze fetch calls.
Installation
$ npm i -S @bsara/react-use-fetch
Basic Usage
Basic Usage (Immediate Execution)
import { useFetchGet } from '@bsara/react-use-fetch';
export function MyComponent() {
const { loading, error, value: movie } = useFetchGet<Movie>('/api/movies/42');
return (
loading ? <div>Loading...</div>
: error ? <div>Error: {error.message}</div>
: <div>{movie.title} ({movie.year}) by {movie.director}</div>
);
}
type Movie = {
id: number;
title: string;
year: number;
director: string;
};
Basic Usage (On-Demand Execution)
import { useState } from 'react';
import { useFetchGetFn } from '@bsara/react-use-fetch';
export function MyComponent() {
const [ { loading, error, value: movie }, fetchMovie ] = useFetchGetFn<Movie>(`/api/movies/42`);
return (
loading ? <div>Loading...</div>
: error ? <div>Error: {error.message}</div>
: movie ? <div>{movie.title} ({movie.year}) by {movie.director}</div>
: <button onClick={fetchMovie}>Fetch It!</button>
);
}
Add "Standard" Options for All Requests (Without Provider)
import { addUseFetchMiddleware } from '@bsara/react-use-fetch';
import standardOptionsMiddleware from '@bsara/react-use-fetch/middleware/standard-options';
addUseFetchMiddleware(standardOptionsMiddleware);
Advanced Usage
TODO
Adding Middleware
TODO
Aborting a Request
TODO
Hooks
Middleware
TODO
Provided Middleware