@soywod/react-use-observable
TypeScript icon, indicating that this package has built-in type declarations

0.0.4Β β€’Β PublicΒ β€’Β Published

πŸ‘€ React use observable npm gh-actions

React hook that consumes any kind of observable via useState.

Installation

npm install @soywod/react-use-observable
# or
yarn add @soywod/react-use-observable

Definition

declare type UseObservable = <T>(obs$: Observable<T>, defaultVal: T, fn?: UseObservableFn<T>) => [T, UseObservableFn<T>];
declare type UseObservableFn<T> = (val: T) => void;

declare const useObservable: UseObservable;

Usage

The observable can be any kind of object with a subscribe and a next property. For eg with RxJS:

counter/service.ts:

import {BehaviorSubject} from "rxjs";

export const counter$ = new BehaviorSubject(0);
export function incrementCounter() {
  counter$.next(count => count + 1);
}

counter/component.tsx:

import React from "react"
import {useObservable} from "@soywod/react-use-observable";

import {counter$, incrementCounter} from "./service"

const MyComponent: FC = () => {
  const [count] = useObservable(counter$, counter$.value);
  return <button onClick={incrementCounter}>{count}</button>;
}

Development

git clone https://github.com/soywod/react-use-observable.git
cd react-use-observable
yarn install

Tests

yarn test

Package Sidebar

Install

npm i @soywod/react-use-observable

Weekly Downloads

0

Version

0.0.4

License

MIT

Unpacked Size

9.1 kB

Total Files

14

Last publish

Collaborators

  • soywod