rxjs-use-store
TypeScript icon, indicating that this package has built-in type declarations

0.1.5 • Public • Published

RxJS-use-store

MIT License npm version codecov

A lightweight state management library for React powered by RxJS, featuring a concise type-safe interface.

Demo

Try out the examples at Codesandbox

Installation

Get it from NPM with your favorite package manager.

  npm install rxjs-use-store
  yarn add rxjs-use-store

Usage/Examples

A minimal store is defined by an initialState and a map of actions. When the useStore hook is called for the first time, the state and callbacks are composed from the given actions.

function MyComponent() {
  type MyState = {myValue: number}
  type AnAction = [number]
  interface MyActions extends ActionsType<MyState> {
    anEffect($: Observable<AnAction>): Observable<((state: MyState) => MyState)>
  }
  const [{anEffect}, state] = useStore<MyState, MyActions, [number]>({
    initialState: {myValue: 1}, 
    actions: {
      anEffect: $ => $.pipe(map((([newValue]) => state => ({myValue: newValue}))))
    }
  })
  return <button onClick={() => anEffect(state.myValue * 2)}>{state.myValue}</button>
}

See the demo.

Each member of actions is a factory function that defines the RxJS plumbing work needed for that kind of action.

  • An action produces an observable of state reducers from the input observable.
  • A callback is generated by the useStore hook for each action.
  • When a callback is invoked, the arguments value is sent to the corresponding input observable.

Callbacks returned from the useStore are type-safe, allowing easy navigation to the action definition and peeking at the accepted parameter types.

It is also possible to wire external observables into the store by defining inputAction and outputAction. See documentation below or checkout examples/ directory for more working samples.

Form Validation Example

Below is a complete example to demonstrate a form component implementation with asynchronous validation.

type MyFormData = {name?: string, email?: string}
const validateFormAsync = ({email}: MyFormData) =>
  of(/^\S+@\S+$/.test(email || "")).pipe(delay(1000))

function MyFormComponent(props: {onSubmit?: (formData: MyFormData) => void}) {
  type FormState = MyFormData & {valid?: boolean}
  
  const [callbacks, state] = useStore({
    initialState: {} as FormState, 
    actions: {
      setName: ($: Observable<[string]>) => $.pipe(
        map(([name]) => (state: FormState) => ({...state, name}))),
      setEmail: ($: Observable<[string]>) => $.pipe(
        map(([email]) => (state: FormState) => ({...state, email})))
    },
    outputAction: ($) => $.pipe(
      switchMap(state => validateFormAsync(state).pipe(
        map((valid) => (latest: FormState) => ({...latest, valid})))))
  })
  
  return <>
    <div>
      Name: <input onChange={e => callbacks.setName(e.target.value)} value={state.name}/>
    </div>
    <div className={state.valid ? "valid" : "invalid"}>
      Email: <input onChange={e => callbacks.setEmail(e.target.value)} value={state.email}/>
    </div>
    <button onClick={() => props.onSubmit?.(state)} disabled={!state.valid}>Submit</button>
  </>
}

Stopwatch Example

A fully functional stopwatch with can be efficiently implemented in 35 lines:

import moment from "moment"
import "moment-duration-format"
import React from "react"
import { interval, Observable, of } from "rxjs"
import { map, mapTo, switchMap, timeInterval } from "rxjs/operators"
import { makeStore, useStore } from "rxjs-use-store"

function StopWatch() {
  type State = {time: number, splits: number[], running: boolean}
  const initialState: State = {time: 0, splits: [], running: false}
  const [actions, state] = useStore(makeStore(
    initialState,
    {
      reset: ($: Observable<[]>) => $.pipe(mapTo(() => initialState)),
      toggle: ($: Observable<[boolean]>) => $.pipe(
        switchMap(([running]) => running ? 
          interval(1).pipe(
            timeInterval(), 
            map(delta => (state: State) => ({...state, time: state.time + delta.interval, running: true}))) :
          of((state: State) => ({...state, running: false})))),
      split: ($: Observable<[number]>) => $.pipe(map(([now]) => state => ({...state, splits: [...state.splits, now]})))
    }))

  return <>
    <div>{moment.duration(state.time, 'ms').format("hh:mm:ss.SS", {trim: false})}</div>
    <button onClick={() => actions.toggle(!state.running)}>{state.running ? "Stop" : "Start"}</button>
    <button onClick={actions.reset} disabled={state.running}>Reset</button>
    <button onClick={() => actions.split(state.time)}>Split</button>
    <div>
      <ol>{state.splits.map(split => 
        <li>{moment.duration(split, 'ms').format("hh:mm:ss.SS", {trim: false})}</li>)}
      </ol>
    </div>
  </>
}

Library Documentation

Store

...

initialState

...

Actions

...

inputAction - Reacting to dependent prop changes

...

outputAction - Reacting to all store updates

...

useStore

rxjs-use-store is inspired by the rxjs-hooks library. Likewise, useStore utilizes the use-constant package under the hood to bind RxJS Subjects into the React component nodes.

Callbacks

...

makeStore(initialState, actions, [options])

This is a convenience function to build your store objects. It helps Typescript compiler with type inference, to avoid having to define explicit type interfaces that may be needed with literal store object definitions.

Contributing/Hacking

If you already cloned the repository, you can run examples via yarn start.

Package Sidebar

Install

npm i rxjs-use-store

Weekly Downloads

1

Version

0.1.5

License

MIT

Unpacked Size

29 kB

Total Files

19

Last publish

Collaborators

  • alimg