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

@immerx/state

v3.2.2

Published

Reactive & fractal state management with Immer

Downloads

8

Readme

Reactive and fractal state management with Immer

Table of contents:

Install

npm install @immerx/state

Immer >= v6.0.0 is a peer dependency so make sure it's installed.

Create

import create from '@immerx/state'

const state$ = create({ count: 0 })

Pretty simple - we create a new state by importing create and call it with an initial state value.

Observe

import create from '@immerx/state'

const state$ = create({ count: 0 })
state$.subscribe({
  next: v => console.log(`Count is: ${v}`),
})
// > Count is: 0

Our state$ is an observable which we can subscribe to and get notified on every state change.

Update

The following examples assume that you already know about Immer, what drafts & producers are and how to use them.

import create from '@immerx/state'

const state$ = create({ count: 0 })
state$.subscribe({
  next: v => console.log(`Count is: ${v}`),
})
// > Count is: 0

state$.update(draft => void draft.count++)
// > Count is: 1

Edit immerx-simple-counter

Our state$ exposes an update method that takes a curried producer in order to update the underlying state object.

Compose

In addition to being reactive, state$ is also fractal, which allows as to create and compose smaller and isolated pieces of state where consumers will be notified only for relevant changes. Updates are also isolated so the consumer doesn't need to know anything about the "global" state:

import create from '@immerx/state'

const state$ = create({ parent: { child: { name: 'foo' } } })

const parentState$ = state$.isolate('parent')
const childState$ = parentState$.isolate('child')

parentState$.subscribe({
  next: v => console.log('parent state: ', v),
})
// > parent state: { child: { name: "foo" } }

childState$.subscribe({
  next: v => console.log('child state: ', v),
})
// > child state: { name: "foo" }

state$.update(draft => void (draft.otherParent = {}))
/* nothing logged after this update */

parentState$.update(parentDraft => void (parentDraft.sibling = 'bar'))
// > parent state: { child: { name: "foo" }, sibling: "bar" }

childState$.update(() => 'baz')
// > parent state: { child: { name: "baz" }, sibling: "bar" }
// > child state: { name: "baz" }

Edit immerx-fractal-example

Combine and compute

More often than we'd like, our consumers need to combine and/or compute different pieces of state, sometimes including parts of its parent state. This type of isolation can be achieved through lenses.

Lenses allow you to abstract state shape behind getters and setters.

import create from '@immerx/state'

const INITIAL_STATE = {
  user: { name: 'John', remainingTodos: [1, 2] },
  todos: ['Learn JS', 'Try immerx', 'Read a book', 'Buy milk'],
}
const state$ = create(INITIAL_STATE)

const user$ = state$.isolate({
  get: state => ({
    ...state.user,
    remainingTodos: state.user.remainingTodos.map(idx => state.todos[idx]),
  }),
  set: (stateDraft, userState) => {
    const idxs = userState.remainingTodos.map(t => {
      const idx = stateDraft.todos.indexOf(t)
      return idx > -1 ? idx : stateDraft.todos.push(t) - 1
    })

    stateDraft.user = { ...userState, remainingTodos: idxs }
  },
})

user$.subscribe({
  next: console.log,
})
// > { name: "John", remainingTodos: [ "Try immerx", "Read a book" ] }

user$.update(userDraft => void userDraft.remainingTodos.push('Say hello'))
// > { name: "John", remainingTodos: [ "Try immerx", "Read a book", "Say hello" ] }

user$.update(userDraft => void userDraft.remainingTodos.splice(1, 1))
// > { name: "John", remainingTodos: [ "Try immerx", "Say hello" ] }

Edit immerx-combine-and-compute

Let's quickly explain what's going on here:

Obviously, it's a very simple todos app where the state seems to have a normalized shape. We use a lens to provide our consumer with an isolated piece of the state (user$) where the getter returns the user object but also expands user.remainingTodos.

get: state => ({
  ...state.user,
  remainingTodos: state.user.remainingTodos.map(idx => state.todos[idx]),
})

The consumer can manipulate the remainingTodos without having any idea that a todos list exists in the parent state and that user.remainingTodos is actually a list of pointers to entries inside todos.

It can safely push the todo text inside the remainingTodos:

user$.update(userDraft => void userDraft.remainingTodos.push('Say hello'))

The lens' setter will take care of updating the parent state while keeping it normalized.

set: (stateDraft, userState) => {
  const idxs = userState.remainingTodos.map(t => {
    const idx = stateDraft.todos.indexOf(t)
    return idx > -1 ? idx : stateDraft.todos.push(t) - 1
  })
  stateDraft.user.remainingTodos = idxs
}

Middleware

Middleware implementations are based around immer patches. We can register functions (middleware) with immerx and they will receive a reference to the state$ and then be invoked with every patch. Based on how and where something was updated in our state, our middleware can perform side-effect and/or update the state.

The middleware signature is very simple:

function middleware(state$) {
  return ({ patches, inversePatches }, state) => {
    /**
     * This function is called for every state update.
     *
     * It receives the list of patches/inversePatches
     * and is closed over the state$ so we can use state$.update()
     * to update the state in response
     */
  }
}

We can now pass our middleware to create and it'll be registered with immerx

import create from '@immerx/state'

import initialState from './state'
import middleware from './middleware'

create(initialState, [middleware])

Check out @immerx/observable - an observable based middleware.

Use with React

Check out the React bindings at @immerx/react

Developer tools

The @immerx/devtools component provides an overview of all the state changes.

There is a Chrome Devtools extension available but it can also be rendered inline, either manually by using the exported React component, or as part of an iframe if you're not using React.