Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ivanross/react-promise-manager

Yet another Promise utility library for React.
https://github.com/ivanross/react-promise-manager

hook promise react

Last synced: 9 days ago
JSON representation

Yet another Promise utility library for React.

Awesome Lists containing this project

README

        

# React Promise Manager

Yet another Promise utility library for React.

- [Getting Started](#getting-started)
- [`usePromise`](#usepromise)
- [`ManagedPromise`](#managedpromise)
- [Accessing PromiseState via function](#accessing-promisestate-via-function)
- [Accessing PromiseState via hook](#accessing-promisestate-via-hook)

## Getting Started

```
npm install react react-promise-manager
```

## `usePromise`

Accepts `Promise | () => Promise` and an array of dependency. Returns PromiseState.

```jsx
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 (


Here's my data! 🎉


{JSON.stringify(promiseResult)}


)
}
```

## `ManagedPromise`

Pass a `Promise | () => Promise` to `ManagedPromise` and with `Resolved`, `Rejected` and `Pending` you can choose what to render accordingly to the promise state.

```jsx
import { ManagedPromise, Pending, Rejected, Resolved } from 'react-promise-manager'

const App = () => (

loading... ⏱
Oops, something went wrong 😞




)
```

### Accessing PromiseState via function

To access the result or the error returned by the promise, a function can be passed to `Resolved` and `Rejected` as child:

```jsx
const App = () => (

{result => }
{error => }

)
```

The same thing can be done with `ManagedPromise` to access PromiseState:

```jsx
const App = () => (

{promiseState => ... }

)
```

### Accessing PromiseState via hook

Alternatively, the result or error of the promise can be accessed with `usePromiseResult` and `usePromiseError`:

```jsx
const MyComponent = () => {
const result = usePromiseResult()
...
}

const MyErrorHandler = () => {
const result = usePromiseError()
...
}

const App = () => (








)
```

Full PromiseState can be accesed with `usePromiseState`:

```jsx
const MyComponent = () => {
const promiseState = usePromiseState()
...
}

const App = () => (



)
```

- `usePromiseState` can be used only in a `ManagedPromise` child
- `usePromiseResult` can be used only in a `Resolved` child
- `usePromiseError` can be used only in a `Rejected` child