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

https://github.com/chrishutchinson/react-async-status

A simple React hook for managing the status of an async action and an associated message
https://github.com/chrishutchinson/react-async-status

async data-loading hooks loading react typescript

Last synced: 4 days ago
JSON representation

A simple React hook for managing the status of an async action and an associated message

Awesome Lists containing this project

README

          

# `useAsyncStatus()` React Hook

> A simple React hook for managing the status of an async action and an
> associated message

[![CircleCI](https://circleci.com/gh/chrishutchinson/react-async-status.svg?style=svg)](https://circleci.com/gh/chrishutchinson/react-async-status)

## Installation

```bash
$ yarn add react-async-status
```

## Usage

`status` can be one of:

- `"none"` – async action not yet initialised
- `"pending"` – async action initialised but not complete
- `"success"` – async action completed successfully
- `"error"` – async action failed

`message` is an optional string

`setStatus` is a method that takes one of the above statuses, and (optionally) a
message string.

```ts
const [status, message, setStatus] = useAsyncStatus();
```

### Simple example

```tsx
import useAsyncStatus from "react-async-status";

const SomeComponent: React.FunctionComponent = () => {
const [loadingStatus, loadingMessage, setLoadingStatus] = useAsyncStatus();

useEffect(() => {
setLoadingStatus("pending");

someAsyncLoadingFunction()
.then(() => {
setLoadingStatus("success");

// ...
})
.catch(err => {
setLoadingStatus("error", err.message);
});
}, []);

if (loadingStatus === "error") {
return

There was an error loading your data: {loadingMessage}
;
}

if (loadingStatus === "pending") {
return

Loading...
;
}

if (loadingStatus === "none") {
return

Your request for data has not started yet
;
}

return

Your data has loaded!
;
};

export default SomeComponent;
```

### Alternative example (custom naming)

```tsx
import useAsyncStatus from "react-async-status";

const SomeComponent: React.FunctionComponent = () => {
const [savingStatus, savingMessage, setSavingStatus] = useAsyncStatus();

const handleSave = async () => {
setSavingStatus("pending");

try {
await saveSomething();

setSavingStatus("success");
} catch (err) {
setSavingStatus("error", err.message);
}
};

return (


{savingStatus === "error" && (

There was an error saving your data: {savingMessage}


)}

{savingStatus === "success" && (

Your data has been saved successfully!


)}

Click the button to save your data


{savingStatus === "pending" ? "Saving..." : "Save"}


);
};

export default SomeComponent;
```

## Development

### Testing

The unit test suite can be run with:

```bash
$ yarn test
```

### Bundling

The library bundles can be generated with:

```bash
$ yarn bundle
```

### Publishing

The package can be published at:

```bash
$ yarn publish
```