Giter Site home page Giter Site logo

immerx-state's Introduction

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.

immerx-state's People

Contributors

dependabot[bot] avatar monojack avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

zhangaz1

immerx-state's Issues

Re-Write in TypeScript?

It would be very nice to have type definitions / completions on my state.
Would you accept a PR for a typescript re-write or do you have any plans on providing some typescript definitions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.