Types:
type PromiseAction : {
// For reloading specified promise to re-run by name
reload: Function<String | Array<String>>,
// For direct updating value to a promise instead of re-run ( reload will still work after update )
update: Function<Map<String, Any>>,
}
type PromiseResponse : {
[key]: Any
}
Provider Component:
Props: {
promise: Map<String, Promise>
}
<AsyncProvider promise={}}>
</AsyncProvider>
Consumer Component:
Props : {
promise: Array<String> | String,
loading: React.Node | Function<React.Node>,
error: React.Node | Function<React.Node>,
children: Function<PromiseResponse, PromiseAction> | Function<PromiseAction>,
}
// Render only when promise resolved, return `PromiseResponse` & `PromiseAction`
<Async promise={[ "value" ]} loading={() => ()} error={() => ()}>
{
({ value }, { reload, update }) => ()
}
</Async>
// Render directly, return `PromiseAction`.
<Async>
{
({ reload, update }) => ()
}
</Async>
Example Usage:
import React from 'react';
import Async, { Provider as AsyncProvider } from 'AsyncProvider';
export default class App extends React.Component {
render() {
<AsyncProvider
promise={{
value: () => Promise.resolve(1),
timeout: () => new Promise(
(resolve) => setTimeout(
() => resolve(1),
3000
)
)
}}
>
<Async>
{
({ reload, update }) => (
<View>
<Button onPress={() => reload('timeout')}>RELOAD</Button>
<Button onPress={() => update({ timeout: 10 })}>UPDATE</Button>
</View>
)
}
</Async>
<Text>|| Just a seperator ||</Text>
<Async
promise={[ "value" ]}
loading={<Text>LOading</Text>}
error={<Text>Errors</Text>}
>
{
({ value }) => <Text>Value : {value}</Text>
}
</Async>
<Text>|| Just a seperator ||</Text>
<Async
promise={[ "value", "timeout" ]}
loading={<Text>Loading</Text>}
error={(error) => <Text>{error.message}</Text>}
>
{
({ value, timeout }, { reload, update }) => <Text>Value : {value}, Timeout: {timeout}</Text>
}
</Async>
</AsyncProvider>
}
};