1.0.0 • Published 4 years ago
react-fetch-decorator v1.0.0
react-fetch-decorator
React Higher-Order Component (HOC) for observing and invoking fetch requests.
Features:
- can rerender component when request status changes
- can abort requests when unmounting component
- can abort request on second call
Installation
npm i react-fetch-decoratorDemo
Usage
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import withActions from 'react-fetch-decorator'
class Dog extends Component {
static propTypes = {
fetchDogAction: PropTypes.object.isRequired,
}
handleClick = () => {
const { fetchDogAction } = this.props
fetchDogAction.run()
}
render() {
const { fetchDogAction } = this.props
const { isPending, isFailed, isSucceded, error, result } = fetchDogAction
return (
<>
<button onClick={this.handleClick}>
Random Dog
</button>
{isPending && (
<div>
Loading...
</div>
)}
{isFailed && (
<div>
{error.message}
</div>
)}
{isSucceded && (
<img src={result.message} />
)}
</>
)
}
}
const mapActionsToProps = {
fetchDogAction: async (signal) => {
const url = 'https://dog.ceo/api/breeds/image/random'
const response = await fetch(url, { signal })
return response.json()
}
}
export default withActions(mapActionsToProps)(Dog)Action run method returns a Promise
...
handleClick = async () => {
const { fetchDogAction } = this.props
try {
const dog = await fetchDogAction.run()
console.log('Fetched dog: ', dog)
}
catch (error) {
console.log('Error occured while fetching a dog: ', error.message)
}
}
...Invoking action with parameters
...
const mapActionsToProps = {
fetchUserAction: (signal) => async (userId) => {
const url = `/users/${userId}`
const response = await fetch(url, { signal })
return response.json()
}
}
...
fetchUserAction.run({
args: [userId]
})
...API
HOC creator params
mapActionsToProps = { ... }- function or object that defines actions. If it's a function then component props will be passed to it.options = { abortPendingOnUnmount: true }
Structure of action object
isDefault-trueif action never ranisPending-trueif action is pendingisSucceded-trueif action has succededisFailed-trueif action has failedresult- result of actionerror- error occured while performing actionrun(runOptions)- starts actionreset(resetOptions)- resets action
runOptions
args = []- arguments will be passed to actionsilent = false- disables throwing errorsabortPending = true- aborts previous action if it still runningupdateComponent = true- allows to rerender component on status changeupdateComponentOnPending = undefinedupdateComponentOnSuccess = undefinedupdateComponentOnFailure = undefined
resetOptions
abortPending = true- aborts pending actionupdateComponent = true- invokes component rerender
1.0.0
4 years ago