@tutanck/resync
v0.0.20
Published
Dead simple async and sync hooks for react
Downloads
7
Maintainers
Readme
Dead simple react async hook
@tutanck/resync offers only 2 hooks :
useAsync: set one or many async functions and allows you to follow their execution status.
useSync: execute a callback whenever at least one of the one or many async functions set as paremeters is 'done'.
Example
import { fetch, add, update, remove } from 'src/api/products';
import { useAsync, useSync, isLoading } from '@tutanck/resync';
export default function App({ onError }) {
const [products, setProducts] = useState([]);
const [[fetchProducts, fetchStatus, fetchProcessId]] = useAsync(fetch);
const fetchAndSet = () => fetchProducts().then(setProducts).catch(onError);
// Will run 'fetchAndSet' whenever
// addStatus, updateStatus or removeStatus
// is equal to 'done'.
const [
[onAddProduct, addStatus, addProcessId],
[onUpdateProduct, updateStatus, updateProcessId],
[onRemoveProduct, removeStatus, removehProcessId]
] = useSync(fetchAndSet, add, update, remove);
const addProduct = onAddProduct(); // no custom id is set => resync will provide an unique id to identify each different call to 'addProduct'
useEffect(fetchAndSet, []); // first fetch
return isLoading(fetchStatus) ? (
<LinearProgress />
) : (
<div>
<Button
disabled={isLoading(addStatus)}
onClick={() => onAddProduct()}
>
Create
</Button>
<Button
disabled={isLoading(removeStatus)}
onClick={(id) => removeProduct(id)()} // with a custom id set to 'id', 'removehProcessId' will be equal to the passed 'id' for each call to removeProduct
>
Delete
</Button>
</div>
);
}
API
useAsync
Syntax
useAsync(...asynFns);
Parameters
- asynFns: Whatever async functions you want. Note that the order matters.
Return value
An array of arrays of 3 elements for each async function passed as parameters in this order:
- An async function handle (asyncFn).
- asyncFn(id)(...args) accepts an optional custom id as first parameter.
- if you don't want to customize the id just set it to undefined.
- An execution status between:
- undefined
- 'loading'
- 'error'
- 'done'
- An unique call id that changes each time the handle is called.
useSync
Syntax
useSync(callbackFn, ...asynFns);
Parameters
- callbackFn: Whatever callback function you want (async or not).
- asynFns: An array of whatever async functions you want. Note that the order matters.
Return value
An array of arrays of 3 elements for each async function passed as parameters in this order :
- An async function handle (asyncFn).
- asyncFn(id)(...args) accepts an optional custom id as first parameter.
- if you don't want to customize the id just set it to undefined.
- An execution status between:
- undefined
- 'loading'
- 'error'
- 'done'
- An unique call id that changes each time the handle is called.