fetch-react v0.4.0
fetch-react ·
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}
/>
Props
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
)
Installation
npm i fetch-react
For older browsers without native fetch support you need a polyfill.
For Node.js usage you need node-fetch.
Usage
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"/>
Fetch options
You can pass options to the fetch
call using the opts
prop.
Valid options are described here.
Default options and base URL
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}/>}
/>
Handling errors in the response
You can throw
from onData
which will render onError
with the thrown error as first argument.
Alternative withFetch
API
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)
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago