https://github.com/azmenak/use-async-reducer
Provides a flexible reducer to simplify handling of async actions
https://github.com/azmenak/use-async-reducer
async hooks pika react react-hooks reducer typescript usereducer utility
Last synced: 5 months ago
JSON representation
Provides a flexible reducer to simplify handling of async actions
- Host: GitHub
- URL: https://github.com/azmenak/use-async-reducer
- Owner: azmenak
- Created: 2019-03-14T17:51:22.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-03T17:50:22.000Z (over 3 years ago)
- Last Synced: 2025-10-06T14:56:19.781Z (8 months ago)
- Topics: async, hooks, pika, react, react-hooks, reducer, typescript, usereducer, utility
- Language: TypeScript
- Size: 402 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# use-async-reducer
An unoppininated hook to help manage async actions in React

[](https://codecov.io/gh/azmenak/use-async-reducer)
[](https://travis-ci.org/azmenak/use-async-reducer)

This package provides only a reducer to manage state, see [use-async-call](https://github.com/azmenak/use-async-call) for an abstraction which manages hook lifecycle and boilerplate reduction
## Install
```
npm install use-async-reducer
```
## Useage
### Basic Example
```ts
import {useEffect} from 'react'
import useAsyncReducer from 'use-async-reducer'
function DataLoadingComponent({id}) {
const [response, actions] = useAsyncReducer()
useEffect(() => {
const fetchData = async () => {
actions.initialize()
try {
actions.success(await Api.fetchUser(id))
} catch (error) {
action.failure(error)
}
}
}, [id])
return (
<>
{response.loading &&
Loading...}
{response.data && {response.data.user.name}}
{response.error && {response.error.message}}
>
)
}
```
### Example with updating data
```ts
import {useEffect, useCallback} from 'react'
import useAsyncReducer, {Loadable} from 'use-async-reducer'
const LoadingIndicator: React.FC> = ({loading, data, error}) => {
if (error) {
return `Error: ${error.message}`
}
if (loading && data === null) {
return 'Loading initial data...'
}
if (loading) {
return 'Updating data...'
}
return null
}
function DataLoadingComponent({id}) {
const [response, actions] = useAsyncReducer()
useEffect(() => {
const fetchData = async () => {
actions.initialize()
try {
actions.success(await Api.fetchUser(id))
} catch (error) {
action.failure(error)
}
}
}, [id])
const updateData = useCallback(async () => {
actions.request()
try {
actions.success(await Api.fetchUser(id))
} catch (error) {
action.failure(error)
}
}, [])
return (
<>
{response.data && (
<>
{JSON.stringify(data, null, 2)}
Refresh Data
>
)}
>
)
}
```