react-fetch-component
react-fetch-component copied to clipboard
React component to declaratively fetch data
react-fetch-component 
React component to declaratively fetch data
Install
yarn add react-fetch-component
or
npm install --save react-fetch-component
Usage
You supply a single function as a child of <Fetch /> which receives a single argument as an object. The function will be called anytime the state of the fetch request changes (for example, before a request has been made, while the request is in flight, and after the request returned a response).
While you can pass a single property to the function (for example, (fetchProps) => ...), it is common to instead use object destructuring to peel off the properties on the object you plan to use.
An example of destructing and using the most common properties loading, error, and data.
<Fetch url="someUrl">
{({ loading, error, data }) => (
<div>
{loading &&
{
/* handle loading here */
}}
{error &&
{
/* handle error here */
}}
{data &&
{
/* handle data here */
}}
</div>
)}
</Fetch>
You can also use React's context via <Fetch.Consumer> for accessing the state in a deep tree (or to create components based on state)
const Loading = () => <Fetch.Consumer>{({ loading }) => loading ? <MySpinner /> : null}</Fetch.Consumer>
const Error = () => <Fetch.Consumer>{({ error }) => error ? <MyError error={error} /> : null}</Fetch.Consumer>
<Fetch url="someUrl">
<div>
<div>
<div>
<Loading />
<Error />
<Fetch.Consumer>
{({ data }) => <div>{ data ? /* handle data here */ : null}</div>}
</Fetch.Consumer>
</div>
</div>
</div>
</Fetch>
Props
url(string) - address of the request. Initial fetch will only be created when it's a non-empty string. You can initially set this toundefined,false, or an empty string to delay the fetch to a later render.options(object|function) - request options such asmethod,headers,credentials, etc. If passed as a function, it will not be evaluated until the request is sent, which is useful when calling expensive methods likeJSON.stringifyforoptions.bodyfor example.- see Request properties for all available options.
as- declare how to handle the response body- default:
auto(will attempt to parse body based onContent-Typeheader) - can either be a string for any of the body methods including:
arrayBufferblobformDatajsontext
- or a
functionthat takes in theresponseand returns aPromise. For example<Fetch as={res => res.text()} /> - or an
objectthat maps theContent-Typeof the response to a function that takes in theresponseand returns aPromise. For example<Fetch as={{ 'application/json': res => JSON.parse(res.text(), customReviver)}} />.html,json,xml, andotherare also available for simplification.
- default:
cache(boolean|object)- If set, will cache responses by
urland return values from cache for matches urls without issues another request. Useful for typeahead features, etc. - If
true, will use an instance ofSimpleCacheper component instance - Can supply an instance with
get(url)andset(url, promise)methods. Passing an instance ofSimpleCacheallows for multiple instances to share the same (simple) cache - Other implementations of a cache can be supplied for more control (LRU, persist to local/sessionStorage, etc)
- default:
false
- If set, will cache responses by
manual(boolean) - Iftrue, requires callingfetchexplicitly to initiate requests. Useful for better control of POST/PUT/PATCH requests.- default:
false
- default:
onDataChange(function) - Function called only when data is changed. It is called beforeonChange, and if a result is returned (i.e. notundefined), this value will be used asdatapassed toonChangeand the child function instead of the original data.onDataChangealso receives the current data as the second parameter, which allows for concatenating data (ex. infinity scroll).onChange(function) - Function called with same props as child function. Useful to callsetState(or dispatch a redux action) since this is not allowed withinrender.onChangewill always be called even if<Fetch />component has been unmounted.- default:
undefined
- default:
fetchFunction(function) - Specify own fetch function. Useful to debounce fetch requests (although probably best to debounce outside of<Fetch />so not call unneccessary renders)- default:
window.fetch
- default:
Object properties passed to child function
-
loading- Set to
truewhile request is in flight - Set to
falseonce response has returned - Set to
nullwhenmanual={true}beforefetch()is called
- Set to
-
error- Is
undefinedwhile request is pending - Will be set to the parsed response body (
jsonby default) if!response.ok(i.e. status < 200 || status >= 300) - Will be set to an
Errorinstance if thrown during the request (ex. CORS issue) or if thrown while attemping to parse the response body, such as returning text/html whenjsonwas expected (which is the default parser) - Will remain
undefinedif neither of the previous occur
- Is
-
data- Is
undefinedwhile request is pending - Set to parsed response body (
jsonby default) unless one of theerrorconditions occur
- Is
-
request- Set to an object containing the props passed to the component (
url,options, etc) when request is sent. - Added for convenience when
<Fetch />is wrapped by your own data component (ex.<UserData />)
- Set to an object containing the props passed to the component (
-
response- Set to the response of the
fetchcall - Useful to check the status code/text, headers, etc
- Set to the response of the
-
fetch- Function that can be called to create a new fetch request (useful when last request had an error or you want to manually refresh the data (see
manualprop)) - The first 2 parameters match
window.fetch(url,options). A third parameter (updateOptions) is available to pass options to the update phase (whereonChange,onDataChange, and the child render function is called). Currently only 1 option is available (ignorePreviousData) which passesundefinedas the current data (second parameter) toonDataChange, which is useful when usingonDataChangeto concatenate data across requests (ie. infinite loading) and the query changes
- Function that can be called to create a new fetch request (useful when last request had an error or you want to manually refresh the data (see
-
clearData- Function to clear data state.
Examples
Include credentials
<Fetch url="someUrl" options={{ credentials: 'include' }}>
{/* ... */}
</Fetch>
More interactive examples on CodeSandbox
See also
- react-odata - uses
<Fetch />for OData endpoints