Socket
Socket
Sign inDemoInstall

@xstate/immer

Package Overview
Dependencies
2
Maintainers
3
Versions
6
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @xstate/immer

XState with Immer


Version published
Weekly downloads
15K
decreased by-47.11%
Maintainers
3
Install size
6.62 kB
Created
Weekly downloads
 

Readme

Source

@xstate/immer


XState Immer
XState with Immer

This package contains utilities for using Immer with XState.

Quick start

Included in @xstate/immer:

  • assign() - an Immer action that allows you to immutably assign to machine context in a convenient way
  • createUpdater() - a useful function that allows you to cohesively define a context update event event creator and assign action, all together. (See an example below)
  1. Install immer, xstate, @xstate/immer:
npm install immer xstate @xstate/immer

Note: You don't need to import anything from immer; it is a peer-dependency of @xstate/immer, so it must be installed.

  1. Import the Immer utilities:
import { createMachine, interpret } from 'xstate';
import { assign, createUpdater } from '@xstate/immer';

const levelUpdater = createUpdater('UPDATE_LEVEL', (ctx, { input }) => {
  ctx.level = input;
});

const toggleMachine = createMachine({
  id: 'toggle',
  context: {
    count: 0,
    level: 0
  },
  initial: 'inactive',
  states: {
    inactive: {
      on: {
        TOGGLE: {
          target: 'active',
          // Immutably update context the same "mutable"
          // way as you would do with Immer!
          actions: assign((ctx) => ctx.count++)
        }
      }
    },
    active: {
      on: {
        TOGGLE: {
          target: 'inactive'
        },
        // Use the updater for more convenience:
        [levelUpdater.type]: {
          actions: levelUpdater.action
        }
      }
    }
  }
});

const toggleService = interpret(toggleMachine)
  .onTransition((state) => {
    console.log(state.context);
  })
  .start();

toggleService.send('TOGGLE');
// { count: 1, level: 0 }

toggleService.send(levelUpdater.update(9));
// { count: 1, level: 9 }

toggleService.send('TOGGLE');
// { count: 2, level: 9 }

toggleService.send(levelUpdater.update(-100));
// Notice how the level is not updated in 'inactive' state:
// { count: 2, level: 9 }

Keywords

FAQs

Last updated on 06 Jun 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc