Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

https://github.com/stefee/react-promise-state-hook

A simple React hook that provides state for async actions.
https://github.com/stefee/react-promise-state-hook

async hook loading promise react react-hooks state

Last synced: 7 days ago
JSON representation

A simple React hook that provides state for async actions.

Awesome Lists containing this project

README

        

# react-promise-state-hook

The `usePromiseState` hook provides you with React state for a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned from an async function, including its **status** (`NOT_STARTED`, `PENDING`, `FULFILLED` or `REJECTED`) and its **resolved** or **rejected** value. The API is heavily inspired by [Apollo GraphQL `useQuery` hook](https://www.apollographql.com/docs/react/data/queries/).

Install:

```sh
npm install react-promise-state-hook
```

Alternatively, you may copy [the source code](https://github.com/stefee/react-promise-state-hook/blob/main/usePromiseState.ts) directly into your project as this library is published under the Unlicense license.

Usage example:

```tsx
import * as React from "react";
import {usePromiseState, PromiseStatus} from "react-promise-state-hook";

const MyApp = () => {
const [fetchCustomer, fetchCustomerState] = usePromiseState(
React.useCallback(async () => {
// Do asynchronous stuff here.
}, []),
);

if (fetchCustomerState.status === PromiseStatus.FULFILLED) {
return ;
}

return (



Start

{fetchCustomerState.status === PromiseStatus.REJECTED && (
Error: {fetchCustomerState.err.message}

)}

);
};
```

## Options

By default, any errors thrown by an async callback will be caught and logged using [`console.error`](https://developer.mozilla.org/en-US/docs/Web/API/console/error).

The `createUsePromiseState` function allows you to set a custom `onError` handler:

```tsx
import {createUsePromiseState} from "react-promise-state-hook";

const handleError = (error: unknown) => {
// Do error reporting here.
};

export const usePromiseState = createUsePromiseState({onError: handleError});
```

```tsx
const [fetchCustomer, fetchCustomerState] = usePromiseState(
React.useCallback(async () => {
// Do asynchronous stuff here.
}, []),
);
```

You can override the `onError` handler when calling `usePromiseState`:

```tsx
const [fetchCustomer, fetchCustomerState] = usePromiseState(
React.useCallback(async () => {
// Do asynchronous stuff here.
}, []),
{
onError: React.useCallback((error: unknown) => {
// Do error reporting here.
}, []),
},
);
```