react-async-hook
Advanced tools
Comparing version 2.0.2 to 2.1.0
@@ -10,2 +10,5 @@ export declare type AsyncState<R> = { | ||
export declare type UseAsyncOptionsNormalized<R> = { | ||
initialState: AsyncState<R>; | ||
executeOnMount: boolean; | ||
executeOnUpdate: boolean; | ||
setLoading: SetLoading<R>; | ||
@@ -17,3 +20,4 @@ setResult: SetResult<R>; | ||
export declare type UseAsyncReturn<R> = AsyncState<R> & { | ||
execute: () => void; | ||
execute: () => Promise<R>; | ||
currentPromise: Promise<R> | null; | ||
}; | ||
@@ -20,0 +24,0 @@ export declare const useAsync: <R, Args extends any[]>(asyncFunction: (...args: Args) => Promise<R>, params: Args, options?: UseAsyncOptions<R>) => UseAsyncReturn<R>; |
@@ -22,2 +22,5 @@ 'use strict'; | ||
const DefaultOptions = { | ||
initialState: InitialAsyncState, | ||
executeOnMount: true, | ||
executeOnUpdate: true, | ||
setLoading: defaultSetLoading, | ||
@@ -54,2 +57,3 @@ setResult: defaultSetResult, | ||
set: promise => (ref.current = promise), | ||
get: () => ref.current, | ||
is: promise => ref.current === promise, | ||
@@ -79,5 +83,14 @@ }; | ||
}); | ||
return promise; | ||
}; | ||
// Keep this outside useEffect, because inside isMounted() | ||
// will be true as the component is already mounted when it's run | ||
const isMounting = !isMounted(); | ||
react.useEffect(() => { | ||
executeAsyncOperation(); | ||
if (isMounting) { | ||
normalizedOptions.executeOnMount && executeAsyncOperation(); | ||
} | ||
else { | ||
normalizedOptions.executeOnUpdate && executeAsyncOperation(); | ||
} | ||
}, params); | ||
@@ -87,2 +100,3 @@ return { | ||
execute: executeAsyncOperation, | ||
currentPromise: CurrentPromise.get(), | ||
}; | ||
@@ -89,0 +103,0 @@ }; |
@@ -1,2 +0,2 @@ | ||
"use strict";var e=require("react");const r={loading:!0,result:void 0,error:void 0},t={setLoading:e=>r,setResult:(e,r)=>({loading:!1,result:e,error:void 0}),setError:(e,r)=>({loading:!1,result:void 0,error:e})},s=(s,n,u)=>{const o=(e=>({...t,...e}))(u),c=(t=>{const[s,n]=e.useState(r);return{value:s,setLoading:()=>n(t.setLoading(s)),setResult:e=>n(t.setResult(e,s)),setError:e=>n(t.setError(e,s))}})(o),l=(()=>{const r=e.useRef(!1);return e.useEffect(()=>(r.current=!0,()=>{r.current=!1}),[]),()=>r.current})(),a=(()=>{const r=e.useRef(null);return{set:e=>r.current=e,is:e=>r.current===e}})(),i=e=>l()&&a.is(e),d=()=>{const e=s(...n);a.set(e),c.setLoading(),e.then(r=>{i(e)&&c.setResult(r)},r=>{i(e)&&c.setError(r)})};return e.useEffect(()=>{d()},n),{...c.value,execute:d}};exports.useAsync=s,exports.useAsyncAbortable=((r,t,n)=>{const u=e.useRef();return s(async(...e)=>{u.current&&u.current.abort();const t=new AbortController;u.current=t;try{return await r(t.signal,...e)}finally{u.current===t&&(u.current=void 0)}},t,n)}); | ||
"use strict";var e=require("react");const t={loading:!0,result:void 0,error:void 0},r={initialState:t,executeOnMount:!0,executeOnUpdate:!0,setLoading:e=>t,setResult:(e,t)=>({loading:!1,result:e,error:void 0}),setError:(e,t)=>({loading:!1,result:void 0,error:e})},n=(n,s,u)=>{const o=(e=>({...r,...e}))(u),c=(r=>{const[n,s]=e.useState(t);return{value:n,setLoading:()=>s(r.setLoading(n)),setResult:e=>s(r.setResult(e,n)),setError:e=>s(r.setError(e,n))}})(o),a=(()=>{const t=e.useRef(!1);return e.useEffect(()=>(t.current=!0,()=>{t.current=!1}),[]),()=>t.current})(),i=(()=>{const t=e.useRef(null);return{set:e=>t.current=e,get:()=>t.current,is:e=>t.current===e}})(),l=e=>a()&&i.is(e),d=()=>{const e=n(...s);return i.set(e),c.setLoading(),e.then(t=>{l(e)&&c.setResult(t)},t=>{l(e)&&c.setError(t)}),e},g=!a();return e.useEffect(()=>{g?o.executeOnMount&&d():o.executeOnUpdate&&d()},s),{...c.value,execute:d,currentPromise:i.get()}};exports.useAsync=n,exports.useAsyncAbortable=((t,r,s)=>{const u=e.useRef();return n(async(...e)=>{u.current&&u.current.abort();const r=new AbortController;u.current=r;try{return await t(r.signal,...e)}finally{u.current===r&&(u.current=void 0)}},r,s)}); | ||
//# sourceMappingURL=react-async-hook.cjs.production.js.map |
@@ -1,2 +0,2 @@ | ||
import{useEffect as r,useRef as t,useState as e}from"react";const n={loading:!0,result:void 0,error:void 0},o={setLoading:r=>n,setResult:(r,t)=>({loading:!1,result:r,error:void 0}),setError:(r,t)=>({loading:!1,result:void 0,error:r})},s=(s,u,c)=>{const l=(r=>({...o,...r}))(c),i=(r=>{const[t,o]=e(n);return{value:t,setLoading:()=>o(r.setLoading(t)),setResult:e=>o(r.setResult(e,t)),setError:e=>o(r.setError(e,t))}})(l),a=(()=>{const e=t(!1);return r(()=>(e.current=!0,()=>{e.current=!1}),[]),()=>e.current})(),d=(()=>{const r=t(null);return{set:t=>r.current=t,is:t=>r.current===t}})(),g=r=>a()&&d.is(r),v=()=>{const r=s(...u);d.set(r),i.setLoading(),r.then(t=>{g(r)&&i.setResult(t)},t=>{g(r)&&i.setError(t)})};return r(()=>{v()},u),{...i.value,execute:v}},u=(r,e,n)=>{const o=t();return s(async(...t)=>{o.current&&o.current.abort();const e=new AbortController;o.current=e;try{return await r(e.signal,...t)}finally{o.current===e&&(o.current=void 0)}},e,n)};export{s as useAsync,u as useAsyncAbortable}; | ||
import{useEffect as r,useRef as e,useState as t}from"react";const n={loading:!0,result:void 0,error:void 0},o={initialState:n,executeOnMount:!0,executeOnUpdate:!0,setLoading:r=>n,setResult:(r,e)=>({loading:!1,result:r,error:void 0}),setError:(r,e)=>({loading:!1,result:void 0,error:r})},u=(u,s,c)=>{const i=(r=>({...o,...r}))(c),a=(r=>{const[e,o]=t(n);return{value:e,setLoading:()=>o(r.setLoading(e)),setResult:t=>o(r.setResult(t,e)),setError:t=>o(r.setError(t,e))}})(i),l=(()=>{const t=e(!1);return r(()=>(t.current=!0,()=>{t.current=!1}),[]),()=>t.current})(),d=(()=>{const r=e(null);return{set:e=>r.current=e,get:()=>r.current,is:e=>r.current===e}})(),g=r=>l()&&d.is(r),v=()=>{const r=u(...s);return d.set(r),a.setLoading(),r.then(e=>{g(r)&&a.setResult(e)},e=>{g(r)&&a.setError(e)}),r},x=!l();return r(()=>{x?i.executeOnMount&&v():i.executeOnUpdate&&v()},s),{...a.value,execute:v,currentPromise:d.get()}},s=(r,t,n)=>{const o=e();return u(async(...e)=>{o.current&&o.current.abort();const t=new AbortController;o.current=t;try{return await r(t.signal,...e)}finally{o.current===t&&(o.current=void 0)}},t,n)};export{u as useAsync,s as useAsyncAbortable}; | ||
//# sourceMappingURL=react-async-hook.es.production.js.map |
@@ -24,2 +24,5 @@ (function (global, factory) { | ||
const DefaultOptions = { | ||
initialState: InitialAsyncState, | ||
executeOnMount: true, | ||
executeOnUpdate: true, | ||
setLoading: defaultSetLoading, | ||
@@ -56,2 +59,3 @@ setResult: defaultSetResult, | ||
set: promise => (ref.current = promise), | ||
get: () => ref.current, | ||
is: promise => ref.current === promise, | ||
@@ -81,5 +85,14 @@ }; | ||
}); | ||
return promise; | ||
}; | ||
// Keep this outside useEffect, because inside isMounted() | ||
// will be true as the component is already mounted when it's run | ||
const isMounting = !isMounted(); | ||
react.useEffect(() => { | ||
executeAsyncOperation(); | ||
if (isMounting) { | ||
normalizedOptions.executeOnMount && executeAsyncOperation(); | ||
} | ||
else { | ||
normalizedOptions.executeOnUpdate && executeAsyncOperation(); | ||
} | ||
}, params); | ||
@@ -89,2 +102,3 @@ return { | ||
execute: executeAsyncOperation, | ||
currentPromise: CurrentPromise.get(), | ||
}; | ||
@@ -91,0 +105,0 @@ }; |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):(e=e||self,t(e["react-async-hook"]={},e.React))}(this,function(e,t){"use strict";const r={loading:!0,result:void 0,error:void 0},n={setLoading:e=>r,setResult:(e,t)=>({loading:!1,result:e,error:void 0}),setError:(e,t)=>({loading:!1,result:void 0,error:e})},s=(e,s,o)=>{const u=(e=>({...n,...e}))(o),c=(e=>{const[n,s]=t.useState(r);return{value:n,setLoading:()=>s(e.setLoading(n)),setResult:t=>s(e.setResult(t,n)),setError:t=>s(e.setError(t,n))}})(u),i=(()=>{const e=t.useRef(!1);return t.useEffect(()=>(e.current=!0,()=>{e.current=!1}),[]),()=>e.current})(),a=(()=>{const e=t.useRef(null);return{set:t=>e.current=t,is:t=>e.current===t}})(),l=e=>i()&&a.is(e),d=()=>{const t=e(...s);a.set(t),c.setLoading(),t.then(e=>{l(t)&&c.setResult(e)},e=>{l(t)&&c.setError(e)})};return t.useEffect(()=>{d()},s),{...c.value,execute:d}};e.useAsync=s,e.useAsyncAbortable=((e,r,n)=>{const o=t.useRef();return s(async(...t)=>{o.current&&o.current.abort();const r=new AbortController;o.current=r;try{return await e(r.signal,...t)}finally{o.current===r&&(o.current=void 0)}},r,n)})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):(e=e||self,t(e["react-async-hook"]={},e.React))}(this,function(e,t){"use strict";const r={loading:!0,result:void 0,error:void 0},n={initialState:r,executeOnMount:!0,executeOnUpdate:!0,setLoading:e=>r,setResult:(e,t)=>({loading:!1,result:e,error:void 0}),setError:(e,t)=>({loading:!1,result:void 0,error:e})},s=(e,s,u)=>{const o=(e=>({...n,...e}))(u),c=(e=>{const[n,s]=t.useState(r);return{value:n,setLoading:()=>s(e.setLoading(n)),setResult:t=>s(e.setResult(t,n)),setError:t=>s(e.setError(t,n))}})(o),i=(()=>{const e=t.useRef(!1);return t.useEffect(()=>(e.current=!0,()=>{e.current=!1}),[]),()=>e.current})(),a=(()=>{const e=t.useRef(null);return{set:t=>e.current=t,get:()=>e.current,is:t=>e.current===t}})(),l=e=>i()&&a.is(e),d=()=>{const t=e(...s);return a.set(t),c.setLoading(),t.then(e=>{l(t)&&c.setResult(e)},e=>{l(t)&&c.setError(e)}),t},f=!i();return t.useEffect(()=>{f?o.executeOnMount&&d():o.executeOnUpdate&&d()},s),{...c.value,execute:d,currentPromise:a.get()}};e.useAsync=s,e.useAsyncAbortable=((e,r,n)=>{const u=t.useRef();return s(async(...t)=>{u.current&&u.current.abort();const r=new AbortController;u.current=r;try{return await e(r.signal,...t)}finally{u.current===r&&(u.current=void 0)}},r,n)})}); | ||
//# sourceMappingURL=react-async-hook.umd.production.js.map |
{ | ||
"name": "react-async-hook", | ||
"version": "2.0.2", | ||
"version": "2.1.0", | ||
"description": "Async hook", | ||
@@ -5,0 +5,0 @@ "author": "Sébastien Lorber", |
183
README.md
@@ -1,10 +0,16 @@ | ||
# react-async-hook | ||
# React-async-hook | ||
[![NPM](https://img.shields.io/npm/dm/react-async-hook.svg)](https://www.npmjs.com/package/react-async-hook) | ||
[![Build Status](https://travis-ci.com/slorber/react-async-hook.svg?branch=master)](https://travis-ci.com/slorber/react-async-hook) | ||
- Simplest way to get async result in your React component | ||
- Typescript support | ||
- Very good, native, typescript support | ||
- Refetch on params change | ||
- Handle concurrency issues if params change too fast | ||
- Flexible, works with any async function, not just api calls | ||
- Support for cancellation (AbortController) | ||
- Possibility to trigger manual refetches / updates | ||
- Options to customize state updates | ||
```jsx | ||
```tsx | ||
const StarwarsHero = ({ id }) => { | ||
@@ -27,3 +33,3 @@ const asyncHero = useAsync(fetchStarwarsHero, [id]); | ||
And the typesafe async function: | ||
And the typesafe async function could be: | ||
@@ -41,6 +47,8 @@ ```tsx | ||
} | ||
return result.json() | ||
return result.json(); | ||
}; | ||
``` | ||
Examples are running on [this page](https://react-async-hook.netlify.com/) and [implemented here](https://github.com/slorber/react-async-hook/blob/master/example/index.tsx) (in Typescript) | ||
# Install | ||
@@ -57,2 +65,167 @@ | ||
# FAQ | ||
#### How can I debounce the request | ||
It is possible to debounce a promise. | ||
I recommend [awesome-debounce-promise](https://github.com/slorber/awesome-debounce-promise), as it handles nicely potential concurrency issues and have React in mind (particularly the common usecase of a debounced search input/autocomplete) | ||
As debounced functions are stateful, we have to "store" the debounced function inside a component. We'll use for that [use-constant](https://github.com/Andarist/use-constant) (backed by `useRef`). | ||
```tsx | ||
const StarwarsHero = ({ id }) => { | ||
// Create a constant debounced function (created only once per component instance) | ||
const debouncedFetchStarwarsHero = useConstant(() => | ||
AwesomeDebouncePromise(fetchStarwarsHero, 1000) | ||
); | ||
// Simply use it with useAsync | ||
const asyncHero = useAsync(debouncedFetchStarwarsHero, [id]); | ||
return <div>...</div>; | ||
}; | ||
``` | ||
#### How can I implement a debounced search input / autocomplete? | ||
This is one of the most common usecase for fetching data + debouncing in a component, and can be implemented easily by composing different libraries. | ||
All this logic can easily be extracted into a single hook that you can reuse. Here is an example: | ||
```tsx | ||
const searchStarwarsHero = async ( | ||
text: string, | ||
abortSignal?: AbortSignal | ||
): Promise<StarwarsHero[]> => { | ||
const result = await fetch( | ||
`https://swapi.co/api/people/?search=${encodeURIComponent(text)}`, | ||
{ | ||
signal: abortSignal, | ||
} | ||
); | ||
if (result.status !== 200) { | ||
throw new Error('bad status = ' + result.status); | ||
} | ||
const json = await result.json(); | ||
return json.results; | ||
}; | ||
const useSearchStarwarsHero = () => { | ||
// Handle the input text state | ||
const [inputText, setInputText] = useState(''); | ||
// Debounce the original search async function | ||
const debouncedSearchStarwarsHero = useConstant(() => | ||
AwesomeDebouncePromise(searchStarwarsHero, 300) | ||
); | ||
const search = useAsyncAbortable( | ||
async (abortSignal, text) => { | ||
// If the input is empty, return nothing immediately (without the debouncing delay!) | ||
if (text.length === 0) { | ||
return []; | ||
} | ||
// Else we use the debounced api | ||
else { | ||
return debouncedSearchStarwarsHero(text, abortSignal); | ||
} | ||
}, | ||
// Ensure a new request is made everytime the text changes (even if it's debounced) | ||
[inputText] | ||
); | ||
// Return everything needed for the hook consumer | ||
return { | ||
inputText, | ||
setInputText, | ||
search, | ||
}; | ||
}; | ||
``` | ||
And then you can use your hook easily: | ||
```tsx | ||
const SearchStarwarsHeroExample = () => { | ||
const { inputText, setInputText, search } = useSearchStarwarsHero(); | ||
return ( | ||
<div> | ||
<input value={inputText} onChange={e => setInputText(e.target.value)} /> | ||
<div> | ||
{search.loading && <div>...</div>} | ||
{search.error && <div>Error: {search.error.message}</div>} | ||
{search.result && ( | ||
<div> | ||
<div>Results: {search.result.length}</div> | ||
<ul> | ||
{search.result.map(hero => ( | ||
<li key={hero.name}>{hero.name}</li> | ||
))} | ||
</ul> | ||
</div> | ||
)} | ||
</div> | ||
</div> | ||
); | ||
}; | ||
``` | ||
#### How to use request cancellation? | ||
You can use the `useAsyncAbortable` alternative. The async function provided will receive `(abortSignal, ...params)` . | ||
The library will take care of triggering the abort signal whenever a new async call is made so that only the last request is not cancelled. | ||
It is your responsability to wire the abort signal appropriately. | ||
```tsx | ||
const StarwarsHero = ({ id }) => { | ||
const asyncHero = useAsyncAbortable( | ||
async (abortSignal, id) => { | ||
const result = await fetch(`https://swapi.co/api/people/${id}/`, { | ||
signal: abortSignal, | ||
}); | ||
if (result.status !== 200) { | ||
throw new Error('bad status = ' + result.status); | ||
} | ||
return result.json(); | ||
}, | ||
[id] | ||
); | ||
return <div>...</div>; | ||
}; | ||
``` | ||
#### How can I keep previous results available while a new request is pending? | ||
It can be annoying to have the previous async call result be "erased" everytime a new call is triggered (default strategy). | ||
If you are implementing some kind of search/autocomplete dropdown, it means a spinner will appear everytime the user types a new char, giving a bad UX effect. | ||
It is possible to provide your own "merge" strategies. | ||
The following will ensure that on new calls, the previous result is kept until the new call result is received | ||
```tsx | ||
const StarwarsHero = ({ id }) => { | ||
const asyncHero = useAsync(fetchStarwarsHero, [id], { | ||
setLoading: state => ({ ...state, loading: true }), | ||
}); | ||
return <div>...</div>; | ||
}; | ||
``` | ||
#### How to refresh / refetch the data? | ||
If your params are not changing, yet you need to refresh the data, you can call `execute()` | ||
```tsx | ||
const StarwarsHero = ({ id }) => { | ||
const asyncHero = useAsync(fetchStarwarsHero, [id]); | ||
return <div onClick={() => asyncHero.execute()}>...</div>; | ||
}; | ||
``` | ||
#### How to support retry? | ||
Use a lib that simply adds retry feature to async/promises directly. Doesn't exist? Build it. | ||
# License | ||
@@ -59,0 +232,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
65526
303
236