# react-hook-use-promise

> A react hook for using promises.

Latest version **3.0.2** (published 2019-08-28) · ISC license · 0 weekly downloads

## Install

```sh
npm install react-hook-use-promise
pnpm add react-hook-use-promise
yarn add react-hook-use-promise
bun add react-hook-use-promise
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 3.0.2 |
| Published | 2019-08-28 |
| First published | 2019-08-18 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 19.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Alexander Biskup |
| Maintainers | abiskup |
| Keywords | react, react-hooks, promise, async, typescript |

## Links

- npm: https://www.npmjs.com/package/react-hook-use-promise
- Repository: https://gitlab.com/AlexBiskup/react-use-promise-hook
- Homepage: https://gitlab.com/AlexBiskup/react-use-promise-hook#readme
- Issues: https://gitlab.com/AlexBiskup/react-use-promise-hook/issues
- npm.io page: https://npm.io/package/react-hook-use-promise

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 3.0.2 (latest) — 2019-08-28
- 3.0.1 — 2019-08-28
- 2.0.0 — 2019-08-26
- 1.0.0 — 2019-08-18

## README

# react-hook-use-promise

usePromise is a react hook that updates the component state with the current Promise state.

## Examples

### 1. Basic usage of usePromise
The hook expects a function that returns a Promise as an argument. If the promise itself was passed as an argument, a new Promise would be created for every rerender.

You can decide when you want to create the Promise by calling `createPromise()` on the hook result.
```tsx
import React from 'react';
import { usePromise, PromiseStatus } from 'react-use-promise-hook';

export function SomeComponent() {

    const [promiseState, createPromise] = usePromise(
        () => Promise.resolve('I´m the promise result.')
    )

    switch (promiseState.status) {
        case PromiseStatus.NotCreated: {
            createPromise();
            return <div>Let´s create the promise.</div>
        }
        case PromiseStatus.Pending: {
            return <div>The promise is currently pending.</div>
        }
        case PromiseStatus.Fulfilled: {
            return <div>{promiseState.value}</div>
        }
        case PromiseStatus.Rejected: {
            return <div>The promise was rejected with reason: {promiseState.reason}</div>
        }
    }

}
```

### 2. usePromise with arguments
The function that returns a promise can also have arguments. This could be useful if you want to create different promises for different user inputs for example.
```tsx
import React from 'react';
import { usePromise, PromiseStatus } from 'react-use-promise-hook';

export function SomeComponent() {

    const [promiseState, createPromise] = usePromise(
        (resultId: number) => Promise.resolve(`I´m the promise result ${resultId}.`)
    )

    switch (promiseState.status) {
        case PromiseStatus.NotCreated: {
            return (
                <div>
                    <button onClick={() => createPromise(1)}>Create Promise 1</button>
                    <button onClick={() => createPromise(2)}>Create Promise 2</button>
                </div>
            )
        }
        case PromiseStatus.Pending: {
            return <div>The promise is currently pending.</div>
        }
        case PromiseStatus.Fulfilled: {
            return <div>{promiseState.value}</div>
        }
        case PromiseStatus.Rejected: {
            return <div>The promise was rejected with reason: {promiseState.reason}</div>
        }
    }

}
```

### 3. usePromise with Promise.all
```tsx
import React from 'react';
import { usePromise, PromiseStatus } from 'react-use-promise-hook';

export function SomeComponent() {

    const [promiseState, createPromise] = usePromise(
        () => Promise.all([
            Promise.resolve('I´m the first result.'),
            Promise.resolve('I´m the second result.'),
        ])
    )

    switch (promiseState.status) {
        case PromiseStatus.NotCreated: {
            createPromise();
            return <div>Let´s create both promises.</div>
        }
        case PromiseStatus.Pending: {
            return <div>The promise is currently pending.</div>
        }
        case PromiseStatus.Fulfilled: {
            return (
                <div>
                    <span>{promiseState.value[0]}</span>
                    <span>{promiseState.value[1]}</span>
                </div>
            )
        }
        case PromiseStatus.Rejected: {
            return <div>The promise was rejected with reason: {promiseState.reason}</div>
        }
    }

}
```
### 4. usePromise with Promise.race
```tsx
import React from 'react';
import { usePromise, PromiseStatus } from 'react-use-promise-hook';

export function SomeComponent() {

    const [promiseState, createPromise] = usePromise(
        () => Promise.race([
            Promise.resolve('I´m the first result.'),
            Promise.resolve('I´m the second result.'),
        ])
    )

    switch (promiseState.status) {
        case PromiseStatus.NotCreated: {
            createPromise();
            return <div>Let´s create both promises.</div>
        }
        case PromiseStatus.Pending: {
            return <div>The promise is currently pending.</div>
        }
        case PromiseStatus.Fulfilled: {
            return (
                <div>
                    <span>The faster one was: {promiseState.value}</span>
                </div>
            )
        }
        case PromiseStatus.Rejected: {
            return <div>The promise was rejected with reason: {promiseState.reason}</div>
        }
    }

}
```

## Promise states
The hook result can be of 4 different types which represent the state of the Promise.

### NotCreated
When you haven´t called the `createPromise()` function yet:
```ts
type PromiseNotCreatedState = {
    status: PromiseStatus.NotCreated;
}
```

### Pending
When the promise is created but neither fulfilled nor rejected yet:
```ts
type PromisePendingState = {
    status: PromiseStatus.Pending
}
```

### Fulfilled
When the promise was fulfilled:
```ts
type PromiseFulfilledState<T> = {
    status: PromiseStatus.Fulfilled;
    value: T;
}
```

### Rejected
When the promise was rejected:
```ts
type PromiseRejectedState = {
    status: PromiseStatus.Rejected;
    reason: any;
}
```

## PromiseSwitch
Is a component which allows you to render the Promise state more conveniently.

### Basic example
```tsx
import React from 'react';
import { usePromise, PromiseSwitch } from 'react-use-promise-hook';

export function SomeComponent() {

    const [promiseState, createPromise] = usePromise(
        () => Promise.resolve('I´m the promise result.')
    )

    return (
        <PromiseSwitch
            state={[promiseState, createPromise]}
            renderOnNotCreated={(createPromise) => <div onClick={createPromise}>The promise hasn´t been created.</div>}
            renderOnPending={() => <div>The promise is pending.</div>}
            renderOnFulfilled={(value) => <div>{value}</div>}
            renderOnRejected={(reason) => <div>Something went wrong: {reason}</div>}
        />
    )

}
```

### Example with createOnNotCreated

If the current promise state is `NotCreated`, you can create the Promise immediately when the PromiseSwich component is mounted.

```tsx
import React from 'react';
import { usePromise, PromiseSwitch } from 'react-use-promise-hook';

export function SomeComponent() {

    const [promiseState, createPromise] = usePromise(
        (name: String) => Promise.resolve(`I´m the promise result ${name}.`)
    )

    return (
        <PromiseSwitch
            state={[promiseState, createPromise]}
            createOnNotCreated={create => create('John')}
            renderOnNotCreated={() => <div>The promise hasn´t been created.</div>}
            renderOnPending={() => <div>The promise is pending.</div>}
            renderOnFulfilled={(value) => <div>{value}</div>}
            renderOnRejected={(reason) => <div>Something went wrong: {reason}</div>}
        />
    )

}
```

---
_Source: https://npm.io/package/react-hook-use-promise · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
