fetch-react ·
fetch-react
is a very small (<4kb) React Higher-Order Component that wraps the Fetch API in a declarative way.
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
const GitHubUser = <Fetch url='https://api.github.com/search/users?q=' + name onData= <img src=dataitems0avatar_url/> onLoading= 'Loading...' onError= '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 = <Fetch url='https://api.example.com/v1/' propsurl opts=fetchOpts ...props /> // then use like <ApiFetch url="/user/11" onData= <User user=user/>/>
Handling errors in the response
You can throw
from onData
which will render onError
with the thrown error as first argument.
withFetch
API
Alternative Component { const fetchResponse fetchError = thisprops if !fetchResponse && !fetchError return <div>Loading!</div> if fetchError return <div>Error!</div> return <img src=fetchResponseavatar_url/> } const url = 'https://api.github.com/search/users?q=alexanderdzhoganov'const fetchOpts = credentials: 'same-origin' const WrappedComponent = MyComponent