dai-shi / React Hooks Fetch
Programming Languages
Projects that are alternatives of or similar to React Hooks Fetch
react-hooks-fetch
React custom hooks for data fetching with Suspense
Important notes
If you are looking for useEffect-based React hooks for Fetch API, please visit https://github.com/dai-shi/react-hooks-async.
This is a library for async functions with Suspense
Introduction
Suspense for data fetching is a new feature coming in React.
This library provides useFetch hook for Render-as-You-Fetch.
It discourages Fetch-on-Render pattern.
Install
npm install react-hooks-fetch
Usage
import React, { Suspense, useTransition } from 'react';
import ReactDOM from 'react-dom';
import { ErrorBoundary, createFetchStore, useFetch } from 'react-hooks-fetch';
const DisplayData = ({ result, refetch }) => {
const [startTransition, isPending] = useTransition({
timeoutMs: 1000,
});
const onClick = () => {
startTransition(() => {
refetch('2');
});
};
return (
<div>
<div>First Name: {result.data.first_name}</div>
<button type="button" onClick={onClick}>Refetch user 2</button>
{isPending && 'Pending...'}
</div>
);
};
const fetchFunc = async (userId) => (await fetch(`https://reqres.in/api/users/${userId}?delay=3`)).json();
const store = createFetchStore(fetchFunc);
store.prefetch('1');
const Main = () => {
const [result, refetch] = useFetch(store, '1');
return <DisplayData result={result} refetch={refetch} />;
};
const App = () => (
<ErrorBoundary fallback={error => <h1>{error.message}</h1>}>
<Suspense fallback={<span>Loading...</span>}>
<Main />
</Suspense>
</ErrorBoundary>
);
ReactDOM.createRoot(document.getElementById('app')).render(<App />);
API
createFetchStore
create fetch store
Parameters
-
fetchFuncFetchFunc<Result, Input> -
preloadedArray<{input: Input, result: Result}>?
Examples
import { createFetchStore } from 'react-hooks-fetch';
const fetchFunc = async (userId) => (await fetch(`https://reqres.in/api/users/${userId}?delay=3`)).json();
const store = createFetchStore(fetchFunc);
store.prefetch('1');
ErrorBoundary
Extends Component
ErrorBoundary with retry support
Examples
import { ErrorBoundary } from 'react-hooks-fetch';
const App = () => (
<ErrorBoundary
fallback={({ error, retry }) => (
<div>
<span>{error.message}</span>
<button type="button" onClick={retry}>Retry</button>
</div>
)}
>
...
</ErrorBoundary>
};
useFetch
useFetch hook
Parameters
-
storeFetchStore<Result, Input> -
initialInputInput?
Examples
import { useFetch } from 'react-hooks-fetch';
const [result, refetch] = useFetch(store, initialInput);
Examples
The examples folder contains working examples. You can run one of them with
PORT=8080 npm run examples:01_minimal
and open http://localhost:8080 in your web browser.
You can also try them in codesandbox.io: 01 02 03
Blogs
See History for previous implementations.
