https://github.com/termosa/use-defer
Simplify work with async functions with memoization and state
https://github.com/termosa/use-defer
Last synced: about 1 year ago
JSON representation
Simplify work with async functions with memoization and state
- Host: GitHub
- URL: https://github.com/termosa/use-defer
- Owner: termosa
- Created: 2020-11-14T05:18:16.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2021-08-16T17:37:18.000Z (almost 5 years ago)
- Last Synced: 2025-03-11T23:16:18.981Z (over 1 year ago)
- Language: TypeScript
- Size: 1.28 MB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-defer
> Simplify work with async functions with memoization and state
[](https://www.npmjs.com/package/use-defer) [](https://standardjs.com)
## Install
```bash
npm install --save use-defer
```
## Usage
```tsx
import * as React from 'react'
import useDefer, { Status } from 'use-defer'
// Or: import { useDefer, Status } from 'use-defer'
const Example = () => {
const {
execute, // Callback for the [asyncFunction] with the same arguments list and result
status, // One of: Status.IDLE - no request, Status.PENDING - waiting for results, Status.SUCCESS & Status.ERROR
value, // Result of the last request
error, // Error thrown during the execution of the last request
} = useDefer(
asyncFunction, // The function that returns a [Promise] instance
[], // Optional list of [React.DependencyList] type to update [asyncFunction]
[], // Optional arguments list. The [asyncFunction] will be called immediately if this is set
);
// ...
};
```
## Examples
### Using it for a single async function
[Source code](https://github.com/termosa/use-defer/blob/master/example/src/SingleFunctionExample.js)
```tsx
const generateNumber = max => new Promise((resolve, reject) => {
if (max > 0) setTimeout(resolve, 2e3, Math.round(Math.random() * max));
else setTimeout(reject, 2e3, 'Max value must be greater than zero');
});
const defaultMax = 100;
const SingleFunctionExample = () => {
const [max, setMax] = React.useState('');
const { value, error, status } = useDefer(
generateNumber, // Async function that returns promise
[max], // Dependencies
[max ? +max : defaultMax] // Initial arguments
);
return (
setMax(e.target.value)}
/>
{status === 'pending' ? processing : null}
{value !== undefined ? Last result: {value} : null}
{error ? Error: {error} : null}
);
};
```
### Create a model hook with auto reloading
[Source code](https://github.com/termosa/use-defer/blob/master/example/src/MultipleFunctionsExample.js)
```tsx
const useResources = () => {
const { execute: reload, value: resources, status } = useDefer(api.get, [], []);
const { execute: create } = useDefer(resource => api.post(resource).then(reload));
const { execute: remove } = useDefer(id => api.delete(id).then(reload));
return { resources, status, create, remove };
};
const MultipleFunctionsExample = () => {
const resourceLabelRef = useRef(null);
const { resources, status, create, remove } = useResources();
const onSubmit = e => {
e.preventDefault();
create({ label: resourceLabelRef.current.value });
resourceLabelRef.current.value = '';
};
return (
{!resources && status === 'pending' ?
Loading...
: null}
{resources
?
{resources.map(res => (
-
{res.label}
{' '}
remove(res.id)} value="remove" />
))}
: null
}
);
};
```
## License
MIT © [termosa](https://github.com/termosa)
---
This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).