Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/artcom/async-task-hook
Provides an react hook for async tasks.
https://github.com/artcom/async-task-hook
Last synced: about 1 month ago
JSON representation
Provides an react hook for async tasks.
- Host: GitHub
- URL: https://github.com/artcom/async-task-hook
- Owner: artcom
- Created: 2020-06-12T15:29:40.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-03-14T23:27:39.000Z (almost 2 years ago)
- Last Synced: 2024-11-07T06:36:18.902Z (3 months ago)
- Language: JavaScript
- Homepage:
- Size: 1.35 MB
- Stars: 0
- Watchers: 14
- Forks: 0
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Async Task Hook
Provides an react hook for async tasks.
## Features
Runs a given async task in a [useEffect](https://reactjs.org/docs/hooks-reference.html#useeffect) hook. The returned state contains the status of the runnning task as well as the result or error. The task completion will be ignored if the component has been unmounted.
Note: The given task function must not change (e.g. wrapped with [useCallback](https://reactjs.org/docs/hooks-reference.html#usecallback)) otherwise a new task (read [useEffect](https://reactjs.org/docs/hooks-reference.html#useeffect)) will be started and the previous result will be ignored.
## States
* `RUNNING` the initial state and the state while the task is running.
* `FINISHED` the final state as soon as the method has finished.
* `ERROR` the final state if the task threw an error.## Example
This example queries content with [axios](https://github.com/axios/axios). The component receives the `url` as property and creates a persistent `queryFunc` which is fed to the async task hook. The returned result can be accessed when the async task has `FINISHED`. If the method throws an exception the status will be set to `ERROR`
```javascript
import axios from 'axios'
import React, { useCallback } from "react"
import { useAsyncTask, RUNNING, FINISHED, ERROR } from "@artcom/async-task-hook"const MyComponent = ({ url }) => {
const queryFunc = useCallback(() => axios.get(url), [url])
const query = useAsyncTask(queryFunc)switch(query.status) {
case RUNNING: return <>Loading...>
case FINISHED: return <>query.result>
case ERROR: return <>query.error>
}
}
```## Tests
Checkout the [tests](./test/useAsyncTask.test.js) for different scenarios.
```bash
npm i && npm run test
```