fetch-react
is a very small (<4kb) React Higher-Order Component that wraps the Fetch API in a declarative way.
<Fetch
url={url}
opts={opts}
onData={onData}
onLoading={onLoading}
onError={onError}
readFn={readFn}
fetchFn={fetchFn}
/>
url
- the request url - a string, URL or Request objectonData
- a function that renders the response dataonLoading
- (optional) a function that renders the loading stateonError
- (optional) a function that renders the error stateopts
- (optional) request options are passed directly tofetch()
readFn
- (optional) function to read the Response body (defaults toresp => resp.json()
)fetchFn
- (optional)fetch()
implementation to use (defaults towindow.fetch
)
npm i fetch-react
For older browsers without native fetch support you need a polyfill.
For Node.js usage you need node-fetch.
import React from 'react'
import Fetch from 'fetch-react'
const GitHubUser = ({ name }) =>
<Fetch
url={'https://api.github.com/search/users?q=' + name}
onData={data => <img src={data.items[0].avatar_url}/>}
onLoading={() => 'Loading...'}
onError={error => 'An error occured!'}
/>
// and use like
<GitHubUser name="alexanderdzhoganov"/>
You can pass options to the fetch
call using the opts
prop.
Valid options are described here.
Wrap the component to set default options or a base URL.
const fetchOpts = { credentials: 'same-origin' }
const ApiFetch = props => <Fetch
url={new URL('https://api.example.com/v1/', props.url)}
opts={fetchOpts}
{ ...props }
/>
// then use like
<ApiFetch
url="/user/11"
onData={user => <User user={user}/>}
/>
You can throw
from onData
which will render onError
with the thrown error as first argument.
import React from 'react'
import { withFetch } from 'fetch-react'
class MyComponent extends React.Component {
render() {
const { fetchResponse, fetchError } = this.props
if (!fetchResponse && !fetchError) {
return <div>Loading!</div>
}
if (fetchError) {
return <div>Error!</div>
}
return <img src={fetchResponse.avatar_url}/>
}
}
const url = 'https://api.github.com/search/users?q=alexanderdzhoganov'
const fetchOpts = { credentials: 'same-origin' }
const WrappedComponent = withFetch(url, fetchOpts)(MyComponent)