npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

rxjs-use-store

v0.1.5

Published

RxJS store pattern with React hooks

Downloads

5

Readme

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.