React hook for fetching data
npm install --save react-use-fetch-hook
import * as React from 'react'
import { useFetch } from 'react-use-fetch-hook'
const fetchUser = () => fetch('/api/me')
interface UserData {
id: string;
name: string;
}
const MyComponent = () => {
const { isLoading, data, error, refetch } = useFetch<UserData>(fetchUser);
if (isLoading) return <div>I'm loading...</div>;
if (error) return <div>Something went wrong :(</div>;
return <div>{user.id}</div>;
};
fetchData
Fetch function that returns a promise....args
Arguments to be passed to fetchData function.
Returns
{ data: S, isLoading, boolean, error: E, refetch: (...args: any[]) => Promise<S> }
data
The response data object resolved by fetchData function.isLoading
Boolean to indicate if request is still loading.error
Error object rejected or thrown by fetchData function.refetch
Function to make a new request.
MIT © ikibalnyi