Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/awmleer/use-async-memo
React hook for generating async memoized data.
https://github.com/awmleer/use-async-memo
async hook react use-memo
Last synced: 18 days ago
JSON representation
React hook for generating async memoized data.
- Host: GitHub
- URL: https://github.com/awmleer/use-async-memo
- Owner: awmleer
- License: mit
- Created: 2019-06-24T06:49:34.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-12-01T06:35:54.000Z (about 1 year ago)
- Last Synced: 2024-04-23T23:46:34.335Z (8 months ago)
- Topics: async, hook, react, use-memo
- Language: TypeScript
- Size: 351 KB
- Stars: 140
- Watchers: 2
- Forks: 9
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- fucking-awesome-react-hooks - `use-async-memo`
- awesome-react-hooks-cn - `use-async-memo`
- awesome-react-hooks - `use-async-memo`
- awesome-react-hooks - `use-async-memo`
README
# useAsyncMemo
React hook for generating async memoized data.
## API
```typescript
function useAsyncMemo(factory: () => Promise, deps: DependencyList, initial?: T): T
```If `factory` returns `undefined` or `null`, `useAsyncMemo` will leave the memoized value **unchanged**.
## Demo
### Import
```js
import {useAsyncMemo} from "use-async-memo"
```### Fetch API:
```js
const data = useAsyncMemo(doAPIRequest, [])
```or
```js
const data = useAsyncMemo(() => doAPIRequest(), [])
```or
```js
const data = useAsyncMemo(() => {
return doAPIRequest()
}, [])
```or
```js
const data = useAsyncMemo(async () => {
return await doAPIRequest()
}, [])
```### Search on inputting:
```js
const [input, setInput] = useState()
const users = useAsyncMemo(async () => {
if (input === '') return []
return await apiService.searchUsers(input)
}, [input], [])
```### Get loading status:
```js
const [loading, setLoading] = useState(true)
const data = useAsyncMemo(async () => {
setLoading(true)
const response = await doAPIRequest()
setLoading(false)
return response
}, [])
```### With ability of manual clearing:
```js
const [input, setInput] = useState()const [clearFlag, setClearFlag] = useState({
val: false
})
function clearItems() {
setClearFlag({
val: true
})
}const users = useAsyncMemo(async () => {
if (clearFlag.val) {
clearFlag.val = false
return null
}
if (input === '') return []
return await apiService.searchUsers(input)
}, [input, clearFlag], [])
```### With debounced value:
> see [use-debounce](https://github.com/xnimorz/use-debounce)```js
const [input, setInput] = useState()
const [debouncedInput] = useDebounce(input, 300)
const users = useAsyncMemo(async () => {
if (debouncedInput === '') return []
return await apiService.searchUsers(debouncedInput)
}, [debouncedInput], [])
```