An open API service indexing awesome lists of open source software.

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

Awesome Lists containing this project

README

          

# use-defer

> Simplify work with async functions with memoization and state

[![NPM](https://img.shields.io/npm/v/use-defer.svg)](https://www.npmjs.com/package/use-defer) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](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 => (

  1. {res.label}
    {' '}
    remove(res.id)} value="remove" />

  2. ))}

: null
}

);
};
```

## License

MIT © [termosa](https://github.com/termosa)

---

This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).