# @jameslnewell/react-observable

> 🎣 React hooks for working with observables.

Latest version **2.0.0-preview.11** (published 2020-03-26) · MIT license · 0 weekly downloads

## Install

```sh
npm install @jameslnewell/react-observable
pnpm add @jameslnewell/react-observable
yarn add @jameslnewell/react-observable
bun add @jameslnewell/react-observable
```

## Health

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

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.0.0-preview.11 |
| Published | 2020-03-26 |
| First published | 2019-05-31 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 48.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Maintainers | jameslnewell |
| Keywords | react, hooks, react-observable, react-hook, react-hooks, observable, observables, jameslnewell |

## Links

- npm: https://www.npmjs.com/package/@jameslnewell/react-observable
- Repository: https://github.com/jameslnewell/react-observable
- Homepage: https://github.com/jameslnewell/react-observable#readme
- Issues: https://github.com/jameslnewell/react-observable/issues
- npm.io page: https://npm.io/package/@jameslnewell/react-observable

## Dependencies (1)

- [@jameslnewell/observable](https://npm.io/package/@jameslnewell/observable.md) ^1.3.0

## 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

- 2.0.0-preview.11 (latest) — 2020-03-26
- 4.0.0-preview.3 (next) — 2021-07-31
- 3.0.0-preview.2 (preview) — 2021-02-18
- 4.0.0-preview.2 — 2021-07-30
- 4.0.0-preview.1 — 2021-07-28
- 3.0.0-preview.12 — 2021-05-27
- 3.0.0-preview.10 — 2021-03-03
- 3.0.0-preview.9 — 2021-02-22
- 3.0.0-preview.8 — 2021-02-20
- 3.0.0-preview.7 — 2021-02-20
- 3.0.0-preview.6 — 2021-02-19
- 3.0.0-preview.5 — 2021-02-19
- 3.0.0-preview.4 — 2021-02-19
- 3.0.0-preview.1 — 2021-02-17
- 2.0.0-preview.9 — 2019-11-01
- … 8 more at https://npm.io/package/@jameslnewell/react-observable/versions

## README

# @jameslnewell/react-observable

![npm (scoped)](https://img.shields.io/npm/v/@jameslnewell/react-observable.svg)
[![Bundle Size](https://badgen.net/bundlephobia/minzip/@jameslnewell/react-observable)](https://bundlephobia.com/result?p=@jameslnewell/react-observable)
[![Actions Status](https://github.com/jameslnewell/react-observable/workflows/main/badge.svg)](https://github.com/jameslnewell/react-observable/actions)

🎣 React hooks for working with observables.

> If you need to work with promises, try [`@jameslnewell/react-promise`](https://github.com/jameslnewell/react-promise).

## Installation

NPM:

```bash
npm install @jameslnewell/react-observable
```

Yarn:

```bash
yarn add @jameslnewell/react-observable
```

## Usage

> [You'll find a working example of `react-observable` in CodeSandbox](https://codesandbox.io/s/jameslnewellreact-observable-sup96).

### useObservable()

Start observing an observable immediately e.g. fetch data from the server when a component is mounted

```js
import React from 'react';
import {fromFetch} from 'rxjs/fetch';
import {switchMap, map} from 'rxjs/operators';
import {useObservable} from '@jameslnewell/react-observable';

const getUser = (id) => {
  return fromFetch(`https://jsonplaceholder.typicode.com/users/${id}`).pipe(
    switchMap((response) => response.json()),
    map((data) => data.username),
  );
};

const UserProfile = ({id}) => {
  const [user, {status, error}] = useObservable(() => getUser(id), [id]);
  switch (status) {
    case 'recieving':
      return <>Loading...</>;
    case 'recieved':
    case 'completed':
      return (
        <>
          Hello <strong>{user}</strong>!
        </>
      );
    case 'errored':
      return <>Sorry, we couldn't find that user.</>;
    default:
      return null;
  }
};
```

### useInvokableObservable()

Start observing an observable when triggered e.g. change data on the server after the user clicks a button

```js
import * as React from 'react';
import {fromFetch} from 'rxjs/fetch';
import {useInvokableObservable} from '@jameslnewell/react-observable';

const putUser = (id, data) => {
  return fromFetch(`https://jsonplaceholder.typicode.com/users/${id}`, {
    method: 'POST',
    body: JSON.stringify(data),
  });
};

const EditUserProfile = ({id}) => {
  const input = React.useRef(null);
  const [save, , {isReceiving}] = useInvokableObservable(
    (data) => putUser(id, data),
    [id],
  );
  const handleSave = async (event) => save(id, {name: input.current.value});
  return (
    <>
      <input ref={input} />
      <button disabled={isReceiving} onClick={handleSave}>
        Save
      </button>
    </>
  );
};
```

## API

### useObservable()

Immediately subscribes to an observable.

#### Parameters:

- `fn` - A function that returns the observable to be observed.
- `deps` - Any value that the function is dependent on and should trigger a new subscription on a new observable.

#### Returns:

- `[0]` - The value observed from the observable.
- `[1].status` - Whether the observable is waiting, recieved, completed or errored.
- `[1].error` - The error observed from the observable.
- `[1].isWaiting` - Whether we're waiting on a value from the observable.
- `[1].isReceieved` - Whether we've recevied a value from the observable.
- `[1].isCompleted`- Whether the observable has completed.
- `[1].isErrored`- Whether the observable has errored.

### useInvokableObservable()

Subscribes to an observable when the `invoke` method is called.

#### Parameters:

- `fn` - A function that returns the observable to be observed.
- `deps` - Any value that the function is dependent on and should trigger a new subscription on a new observable.

#### Returns:

- `[0]` - A function to invoke the observable.
- `[1]` - The value observed from the observable.
- `[2].status` - Whether the observable is waiting, recieved, completed or errored.
- `[2].error` - The error observed from the observable.
- `[2].isWaiting` - Whether we're waiting on a value from the observable.
- `[2].isReceieved` - Whether we've recevied a value from the observable.
- `[2].isCompleted`- Whether the observable has completed.
- `[2].isErrored`- Whether the observable has errored.

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