Yet another Promise utility library for React.
npm install react react-promise-manager
Accepts Promise<T> | () => Promise<T>
and an array of dependency. Returns PromiseState.
import { usePromise } from 'react-promise-manager'
const App = () => {
const promiseState = usePromise(fetchMyData, [])
if (promiseState.state === 'pending') return 'loading... ⏱'
if (promiseState.state === 'rejected') {
return `Oops, something went wrong 😞: ${promiseState.error}`
}
const { result } = promiseState
return (
<div>
<h1>Here's my data! 🎉</h1>
<pre>{JSON.stringify(promiseResult)}</pre>
</div>
)
}
Pass a Promise<T> | () => Promise<T>
to ManagedPromise
and with Resolved
, Rejected
and Pending
you can choose what to render accordingly to the promise state.
import { ManagedPromise, Pending, Rejected, Resolved } from 'react-promise-manager'
const App = () => (
<ManagedPromise promise={fetchMyData}>
<Pending>loading... ⏱</Pending>
<Rejected>Oops, something went wrong 😞</Rejected>
<Resolved>
<MyComponent />
</Resolved>
</ManagedPromise>
)
To access the result or the error returned by the promise, a function can be passed to Resolved
and Rejected
as child:
const App = () => (
<ManagedPromise promise={myPromise}>
<Resolved>{result => <MyComponent result={result} />}</Resolved>
<Rejected>{error => <MyErrorHandler error={error} />}</Rejected>
</ManagedPromise>
)
The same thing can be done with ManagedPromise
to access PromiseState:
const App = () => (
<ManagedPromise promise={myPromise}>
{promiseState => ... }
</ManagedPromise>
)
Alternatively, the result or error of the promise can be accessed with usePromiseResult
and usePromiseError
:
const MyComponent = () => {
const result = usePromiseResult()
...
}
const MyErrorHandler = () => {
const result = usePromiseError()
...
}
const App = () => (
<ManagedPromise promise={myPromise}>
<Resolved>
<MyComponent />
</Resolved>
<Rejected>
<MyErrorHandler />
</Rejected>
</ManagedPromise>
)
Full PromiseState can be accesed with usePromiseState
:
const MyComponent = () => {
const promiseState = usePromiseState()
...
}
const App = () => (
<ManagedPromise promise={myPromise}>
<MyComponent />
</ManagedPromise>
)
usePromiseState
can be used only in aManagedPromise
childusePromiseResult
can be used only in aResolved
childusePromiseError
can be used only in aRejected
child