View Source

Async

A higher-order component for rendering data that isn't ready yet.

There are plenty of situations where you need to fetch content to be displayed, but want to show some sort of loading graphic in the interim. This component helps to simplify that pattern by handling common types of promises and providing a simple mechanism for materializing the fulfilled payload into JSX.

Installation#

npm i --save boundless-async

Async can also just be directly used from the main Boundless library. This is recommended when you're getting started to avoid maintaining the package versions of several components:

npm i boundless --save

the ES6 import statement then becomes like:

import { Async } from 'boundless';

Props#

Required Props#

NameImplementationDescription
children
Expects
function or any renderable or Promise
Default Value
<div />

a promise, function that returns a promise, or other type of renderable content; if a function is passed, it will be called with the current props

Promise example:

const listDataPromise = fetch('/some/list/data/endpoint').then(
    (response) => response.ok ? response.json() : 'Failed to receive list data',
    (error) => error.message,
).then((payload) => {
    if (typeof payload === 'string') {
        return (<div className='error'>{payload}</div>);
    }

    return (
        <ul>
            {payload.map((item) => (<li key={item.id}>{item.content}</li>))}
        </ul>
    );
});

<Async>{listDataPromise}</Async>

Function example, reading in [data-endpoint] as the window.fetch() target:

const fetchListData = (props) => fetch(props['data-endpoint']).then(
    (response) => response.ok ? response.json() : 'Failed to receive list data',
    (error) => error.message,
).then((payload) => {
    if (typeof payload === 'string') {
        return (<div className='error'>{payload}</div>);
    }

    return (
        <ul>
            {payload.map((item) => (<li key={item.id}>{item.content}</li>))}
        </ul>
    );
});

<Async data-endpoint='/some/list/data/endpoint'>{fetchListData}</Async>

Optional Props#

NameImplementationDescription
*
Expects
any

any React-supported attribute

childrenDidRender
Expects
function
Default Value
() => {}

a callback for when real content has been rendered; this will be called immediately if normal JSX is passed to Async, or, in the case of a promise, upon resolution or rejection

pendingContent
Expects
any renderable
Default Value
<div />

content to be shown while the promise is in "pending" state (like a loading graphic, perhaps)