Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/axtk/react-progressive-callback
A React hook for tracking the state of an async action
https://github.com/axtk/react-progressive-callback
async promise react react-hooks
Last synced: 12 days ago
JSON representation
A React hook for tracking the state of an async action
- Host: GitHub
- URL: https://github.com/axtk/react-progressive-callback
- Owner: axtk
- Created: 2022-08-05T21:34:01.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2022-11-05T09:23:36.000Z (about 2 years ago)
- Last Synced: 2024-12-25T23:51:33.432Z (12 days ago)
- Topics: async, promise, react, react-hooks
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/react-progressive-callback
- Size: 83 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# react-progressive-callback
*A React hook for tracking the state of async actions*
Once the state of an async callback (whether it's pending or settled) becomes relevant, the `useProgressiveCallback()` hook comes in as a handy replacement for the React's `useCallback()`. We could have started with something like:
```jsx
let fetchUsers = useCallback(async () => {
let response = await fetch('/users');
return await response.json();
}, []);
```and as soon as the state of this callback becomes required, we only have to make a slight change in the code:
```jsx
let [state, fetchUsers] = useProgressiveCallback(async () => {
let response = await fetch('/users');
return await response.json();
}, []);
```As a typical use case, the state of an async callback can be used in the component to render an error message if it's `'rejected'` or a process indicator unless it's `'fulfilled'`, as shown in the example below.
## Example
```jsx
import {useState, useEffect} from 'react';
import {useProgressiveCallback} from 'react-progressive-callback';export const UserList = () => {
let [users, setUsers] = useState();// the `state` value reflects the state of the async callback
let [state, fetchUsers] = useProgressiveCallback(async () => {
let response = await fetch('/users');
return await response.json();
}, []);
// the second parameter of the hook is an array of dependencies
// serving the same purpose as in the React's `useCallback()` hookuseEffect(() => {
fetchUsers().then(users => {
// in this example, the result is stored in a local state,
// but it could as well be stored in an external store
setUsers(users);
});
}, [fetchUsers]);if (state === 'rejected')
return ;if (state !== 'fulfilled') // 'pending' or undefined
return ;return (
- {name} )}
{users.map(({id, name}) =>
);
};
```