Declarative promise handling in React.
Handling promise-returning functions (for example, fetch
) is not hard to do in React application. There are several packages like holen or React Request for simplifying such kind of tasks but theirs authors try to impose their own vision on various aspects of data fetching. For instance, React Request has a cache for HTTP requests but what will happen if you decide to change caching strategy? React Async Call tries to sharpen the edges. This is minimalistic package that can be used not only for data fetching but also for handling any promise-returning functions.
npm i react-async-call --save
Then, use it as usual:
// using ES6 modules
import createAsyncCallComponent from 'react-async-call'
// using CommonJS modules
var createAsyncCallComponent = require('react-async-call').createAsyncCallComponent
The UMD build is also available on unpkg:
<script src="https://unpkg.com/react-async-call"></script>
The package is avalable on window.ReactAsyncCall
import createAsyncCallComponent from 'react-async-call'
const AsyncCall = createAsyncCallComponent(value => Promise.resolve(42))
const Example = () => (
<AsyncCall>
<AsyncCall.Running>
<div>Loading...</div>
</AsyncCall.Running>
<AsyncCall.Resolved>{({ result }) => <div>The result of function call is {result}</div>}</AsyncCall.Resolved>
<AsyncCall.Rejected>{({ rejectReason }) => <div>Error: {rejectReason}</div>}</AsyncCall.Rejected>
</AsyncCall>
)
createAsyncCallComponent(fn, [displayName])
⇒ AsyncCall
A factory function that creates React component class and binds async operation to it:
const Fetcher = createAsyncCallComponent(() => fetch('https://api.github.com/repositories').then(data => data.json()))
After calling of this function you can use returned component and its static sub-components to hook async operation lifecycle:
// Start executing async operation on Fetcher mount
<Fetcher>
<Fetcher.Running>
Renders only if async operation is executing
</Fetcher.Running>
<Fetcher.Resolved>
{({ result }) => (
<div>
Renders if async operation has been executed successfully
<pre>{JSON.stringify(result)}></pre>
</div>
)}}
</Fetcher.Resolved>
<Fetcher.Rejected>
Renders only if async operation failed
</Fetcher.Rejected>
</Fetcher>
createAsyncCallComponent
is the only member exported by react-async-call package.
Kind: global function
Params
Param | Type | Default | Description |
---|---|---|---|
fn | AsyncFunction |
See AsyncFunction signature for details. |
|
[displayName] | String |
"AsyncCall" |
Component name (visible, for example, in React extension of Chrome Dev Tools). |
Returns: AsyncCall
- Returns React component class AsyncCall
for the further usage.
This class contains extra component classes Running
,
Rejected
, Resolved
,
Completed
, ResultStore
,
Executor
and State
which can be used as children
(direct or indirect) of AsyncCall
.
React Component. This class is returned by call of createAsyncCallComponent and this is the only way to get it.
Kind: global class
Extends: React.Component
Properties
Name | Type | Default | Description |
---|---|---|---|
children | ReactNode | AsyncCallChildrenFunction |
Property children can be either a ReactNode or a function that receives an object as its only argument and return ReactNode. AsyncCall component always renders its children. We recommend to use the first form of using children property and respond to async operation execution results using static sub-components (like Running , Rejected , Resolved , Completed , ResultStore , Executor and State ). |
|
params | any |
A value that will be passed as a single argument into async function. Every time when change of this property occurs, asyncronous operation restarts. | |
[lazy] | Boolean |
false |
If true , component will not start execution of asynchronous operation during component mount phase and on params property change. You should start async operation manualy by calling execute method or via Executor . |
- AsyncCall ⇐
React.Component
- instance
- static
- .ResultStore ⇐
React.Component
- instance
- static
- .HasResult ⇐
React.StatelessComponent
- .Resetter ⇐
React.StatelessComponent
- .HasResult ⇐
- .Running ⇐
React.StatelessComponent
- .Resolved ⇐
React.StatelessComponent
- .Rejected ⇐
React.StatelessComponent
- .Executor ⇐
React.StatelessComponent
- .State ⇐
React.StatelessComponent
- .Completed ⇐
React.StatelessComponent
- .ResultStore ⇐
Method for executing async operation manually.
It is recommended to use <Executor>
component instead.
Kind: instance method of AsyncCall
React Component. Implements store of results of sequential async calls. Useful when you need to accumulate results of async calls (e.g., to glue together sequential calls of server API).
Kind: static class of AsyncCall
Extends: React.Component
Properties
Name | Type | Default | Description |
---|---|---|---|
children | ResultStoreChildrenFunction | ReactNode |
React children or function that returns rendered result depending on hasResult flag and result . |
|
reduce | ReduceFunction |
Function from previousResult and currentResult to a new result. Useful, for example, when you need to accumulate sequential async calls (e.g. for fetching data for infinte page scroll). | |
[initialValue] | any |
Optional initial value for the result store. If value is provided, result store will have result always. | |
[reset] | boolean |
false |
@deprecated If true , clears the store (Deprecated, will be removed in version 1.0.0. Use Resetter instead). |
- .ResultStore ⇐
React.Component
- instance
- static
- .HasResult ⇐
React.StatelessComponent
- .Resetter ⇐
React.StatelessComponent
- .HasResult ⇐
Resets result store to its initial state.
Kind: instance method of ResultStore
Params
Param | Type | Default | Description |
---|---|---|---|
[execute] | bool |
true |
Wether execute promise-returning function after resetting or not. |
React Component. Renders its children whenever result store is not empty (has result).
Property children
must be a function with the only argument receiving object with the only field result
.
Kind: static class of ResultStore
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | HasResultChildrenFunction |
React Component. Renders its children always. Property children
must be a function with the only argument receiving an object
with a function for manual reset of ResultStore.
Kind: static class of ResultStore
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | ResetterChildrenFunction |
React Component. Renders its children whenever async operation was started but is still executing. Otherwise renders nothing.
Kind: static class of AsyncCall
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | ReactNode |
React Component. Renders its children whenever async operation has been completed successfully (promise was resolved),
but is still not started again. Otherwise renders nothing.
Property children
can be either React node(s) or children function with the only argument receiving object with the only field result
.
Kind: static class of AsyncCall
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | ReactNode | ResolvedChildrenFunction |
React Component. Renders its children whenever async operation has been completed with failure (promise was rejected),
but is still not started again. Otherwise renders nothing.
Property children
can be either React node(s) or children function with the only argument receiving object with the only field rejectReason
(promise reject reason).
Kind: static class of AsyncCall
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | ReactNode | RejectedChildrenFunction |
React Component. Renders its children always. Property children
must be a function with the only argument receiving an object
with a function for manual execution of async operation.
Kind: static class of AsyncCall
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | ExecutorChildrenFunction |
React Component. Renders its children always. Property children
must be a function
with the only argument receiving an object (see description of StateChildrenFunction
)
with the state of async operation. State
component is handy for complicated UI cases when none of static components of AsyncCall suits you.
Kind: static class of AsyncCall
Extends: React.StatelessComponent
Properties
Name | Type |
---|---|
children | StateChildrenFunction |
React Component. Renders its children whenever async operation has been completed (successfully or not), but is still not started again. Otherwise renders nothing.
<AsyncCall.Completed>
Async operation completed
</AsyncCall.Completed>
Kind: static class of AsyncCall
Extends: React.StatelessComponent
Properties
Name | Type | Description |
---|---|---|
[children] | ReactNode |
React children to be rendered whenever async operation is completed. |
Type of children
function of a ResultStore component.
Params
Param | Type | Description |
---|---|---|
params | object |
|
params.hasResult | boolean |
|
[params.result] | any |
|
params.reset | ResetFunction |
Function for manual store cleaning. |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Type of reduce
property of a ResultStore component.
Params
Param | Type |
---|---|
previousResult | any |
currentResult | any |
Type of children function for HasResult
Params
Param | Type |
---|---|
params | object |
params.result | any |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Reset function
Params
Param | Type | Default | Description |
---|---|---|---|
[execute] | bool |
false |
Wether execute promise-returning function after resetting or not. |
Type of children function for Resetter
Params
Param | Type | Description |
---|---|---|
params | object |
|
params.reset | ResetFunction |
Function for manual clearing of ResultStore. |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Asynchronous function (aka asynchronous operation or promise-returning function) which returns promise based on supplied parameter.
Params
Param | Type | Description |
---|---|---|
params | any |
Parameters, based on which function should return promise. |
Returns: Promise
- Promise object that represents asynchronous operation result.
Example
The function below returns result (Promise
object) of getting user data from GitHub API by his/her GitHub login:
const getGitHubUserData = userName => fetch(`https://api.github.com/users/${userName}`).then(data => data.json())
Execute function
Type of children function for AsyncCall
Params
Param | Type | Description |
---|---|---|
params | object |
Represents current status of asynchronous operation. |
params.running | boolean |
Indicates whether asynchronous operation is executing or not. |
params.rejected | boolean |
Indicates whether asynchronous operation was failed when it was called last time. If true , result of promise rejection (error) can be found in the params.rejectReason . |
params.resolved | boolean |
Indicates whether asynchronous operation was succeeded when it was called last time. If true , result of promise resolving can be found in the params.result . |
[params.result] | any |
Contains result of promise (returned by async function) resolving if function call was successful. undefined if asynchronous operation is running or promise was rejected. |
[params.rejectReason] | any |
Contains result of promise (returned by async function) rejection if function call was unsuccessful. undefined if asynchronous operation is running or promise was resolved. |
params.execute | ExecuteFunction |
Function for manual execution of asynchronous operation. |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Type of children function for Resolved
Params
Param | Type |
---|---|
object |
|
params.result | any |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Type of children function for Rejected
Params
Param | Type |
---|---|
params | object |
params.rejectReason | any |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Type of children function for Executor
Params
Param | Type | Description |
---|---|---|
params | object |
|
params.execute | ExecuteFunction |
Function for manual execution of asynchronous operation. |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Type of children function for State
Params
Param | Type | Description |
---|---|---|
params | object |
|
params.running | boolean |
Whether async opertation is executing or not. If you only need to process running , use either Running or Completed component instead. |
params.resolved | boolean |
Whether async opertation was completed successfully last time or not. If you only need to process resolved and result , Resolved component instead. |
params.rejected | boolean |
Whether async opertation failed last time or not. If you only need to process rejected and rejectedStatus , use Rejected component instead. |
[params.rejectReason] | any |
Contains reject reason if async opertation failed last time. If you only need to process rejected and rejectedReason , use Rejected component instead. |
[params.result] | any |
Contains result of last successful async operation call. If you only need to process resolved and result , use Resolved component instead. If you need to accumulate result, consider ResultStore usage. |
params.execute | ExecuteFunction |
Callback for manual execution of async operation. If you only need to execute async operation manualy, use Executor component instead. |
Returns: ReactNode
- Should return rendered React component(s) depending on supplied params.
Great thanks to @kitos and @ventrz for their invaluable help, support and bright ideas!