use-async-request v1.2.10
📦 use-async-request
A custom React Hook for async request.

🎨 Features
- 🌟 Make async request w/ loading state, and the request is cancellable
- 🌈 Support multi resquest (request sequentially by default)
- 🎁 Ship React UI component
<AsyncRequest /> - 💪 Type safety
- ☘️ Size ≈ 1.2KB
🔗 Installation
npm install --save use-async-request
OR
yarn add use-async-request🔗 CDN
If you are working w/ UNPKG
https://unpkg.com/use-async-request@1.1.0/lib/umd/use-async-request.min.js
🔗 Usage
👉 useAsyncRequest()
import { useAsyncRequest } from 'use-async-request'
async function getStoryById(params: Record<string, any>) {
return axios({
url: `item/${params.storyId}.json?print=pretty`,
method: 'get',
params,
errorTitle: 'Get Hacker News new stories failed',
signal: params.controller?.signal
})
}
const Story: React.FC<{ storyId: number }> = ({ storyId }) => {
const { data, loading, error, refetch, request, reset } = useAsyncRequest<any>({
defaultData: null,
requestFunctions: [{
func: getStoryById,
payload: {
storyId
},
}],
})
return (
<div>
{loading && <p>Loading...</p>}
{error && <p>{error.message}</p>}
{(data && data[0] && (
<>
<p><a href={data[0].url}>{data[0].title}</a></p>
<p>{data[0].by}</p>
</>
)) || <div></div>}
<div>
<Button onClick={() => refetch()}>Refetch</Button>
<Button onClick={() => reset()}>Reset</Button>
</div>
</div>
)
}👉 <AsyncRequest />
<AsyncRequest
requestFunctions={[
{
func: getStoryById,
payload: { storyId }
}
]}
success={StorySuccess}
loading={
<span>Loading...</span>
}
error={({ error, refetch }) => (
<div>
{error.message}
<button onClick={() => refetch()}>refetch</button>
</div>
)}
/>
async function getStoryById(params) {
return axios({
url: `https://hacker-news.firebaseio.com/v0/item/${params.storyId}.json?print=pretty`,
method: 'get',
params,
errorTitle: 'Get Hacker News story failed',
signal: params.controller?.signal,
});
}
const StorySuccess = ({ data, refetch }) => {
const { title = "", url = "", by = "" } = data?.[0];
return (
<section>
<p><a href={url}>{title}</a></p>
<p>{by}</p>
<button onClick={() => refetch()}>refetch</button>
</section>
);
};Options
defaultDataThe default data to render.
Type: any
Default: null
requestFunctionsThe request APIs goes here. you can set payload and transform function for every single request.
Type: RequestFunction<TData>[]
Default: []
requestFunctions.funcThe request function
Type: (...args: any[]) => Promise<any>
requestFunctions.payloadThe request function should be like below. params can take instance of AbortController in order to cancel request.
async function getStoryIds(params) {
return axios({
url: `${params.storyType}.json?print=pretty`,
method: 'get',
params,
errorTitle: 'Get Hacker News new stories failed',
signal: params.controller?.signal
})
}Type: (...args: any[]) => Promise<any>
requestFunctions.transformyou can use this option to process the data that receive from Api
Type: (res: any) => TData
autousing this option to make request run automatically
Type: boolean
Default: true
persistentEnable data persistent. If set it
true, the data that request from api will store intolocalStoragewith given key(persistentKey), and then the next request data will be load from localStorage instead. The persistent data will always be available untilpersistentExpirationdate.
⚠️ NOTE:refetch()andrequest()will ignorepersistent, it will always load data through api function, AND refresh theexpirationdate.
Type: boolean
Default: false
persistentKeyThe prefix key of the persisted data, which the entire key base on it. The entire key will generate like below:
⚠️ NOTE: This option needs to be set withpersistentat the same time.
// generate key
const key = `${persistentKey}-${JSON.stringify(
requestFunctions.map((req) => {
return { name: req.func.name, payload: req.payload }
})
)}`Type: string
Default: ''
persistentExpirationThe expiration time. (ms)
Type: number
Default: 1000 * 60
Returns
dataThe data that you request
loadingThe loading statement
Type: boolean
errorrefetchretrigger the request action
Type: () => void
requestIf you want to request data manually, use this.
Type: () => Promise<(Data | null)[] | null>
resetBack to the start, render using the
defaultData
Type: () => void
🔗 Roadmap
- Batch async request
<AsyncRequest />React UI components w/ demo- Add
sequentiallyoption for multi requests - persistent
- More detail docs