{"name":"@xstate/react","version":"2.0.0-pr2674-20219612435","description":"XState tools for React","keywords":["state","machine","statechart","scxml","state","graph","react","hook"],"author":{"name":"David Khourshid","email":"davidkpiano@gmail.com"},"homepage":"https://github.com/davidkpiano/xstate/tree/main/packages/xstate-react#readme","license":"MIT","main":"lib/index.js","module":"es/index.js","types":"lib/index.d.ts","typesVersions":{"<4.0":{"lib/index.d.ts":["index.v3.d.ts"]}},"sideEffects":false,"directories":{"lib":"lib","test":"test"},"repository":{"type":"git","url":"git+ssh://git@github.com/davidkpiano/xstate.git"},"scripts":{"clean":"rm -rf dist lib tsconfig.tsbuildinfo","build":"tsc && tsc --outDir es --module es2015 && rollup -c","test":"jest","prepublish":"npm run build && npm run test"},"bugs":{"url":"https://github.com/davidkpiano/xstate/issues"},"peerDependencies":{"@xstate/fsm":"^1.0.0","react":"^16.8.0 || ^17.0.0","xstate":"^4.26.0-pr2674-20219612435"},"peerDependenciesMeta":{"@xstate/fsm":{"optional":true},"xstate":{"optional":true}},"dependencies":{"use-isomorphic-layout-effect":"^1.0.0","use-subscription":"^1.3.0"},"devDependencies":{"@rollup/plugin-commonjs":"^17.0.0","@rollup/plugin-node-resolve":"^11.0.1","@testing-library/react":"^8.0.9","@types/jsdom":"^12.2.3","@types/react":"^16.9.11","@types/react-dom":"^16.9.4","@xstate/fsm":"*","jest":"^26.6.3","jsdom":"^14.0.0","jsdom-global":"^3.0.2","lerna-alias":"3.0.3-0","react":"^16.12.0","react-dom":"^16.12.0","rollup":"^2.35.1","rollup-plugin-replace":"^2.2.0","rollup-plugin-terser":"^5.1.2","rollup-plugin-typescript2":"^0.30.0","ts-jest":"^26.5.6","typescript":"^4.3.5","xstate":"*"},"readme":"# @xstate/react\n\n[[toc]]\n\n## Quick Start\n\n1. Install `xstate` and `@xstate/react`:\n\n```bash\nnpm i xstate @xstate/react\n```\n\n**Via CDN**\n\n```html\n<script src=\"https://unpkg.com/@xstate/react/dist/xstate-react.umd.min.js\"></script>\n```\n\nBy using the global variable `XStateReact`\n\nor\n\n```html\n<script src=\"https://unpkg.com/@xstate/react/dist/xstate-react-fsm.umd.min.js\"></script>\n```\n\nBy using the global variable `XStateReactFSM`\n\n2. Import the `useMachine` hook:\n\n```js\nimport { useMachine } from '@xstate/react';\nimport { createMachine } from 'xstate';\n\nconst toggleMachine = createMachine({\n  id: 'toggle',\n  initial: 'inactive',\n  states: {\n    inactive: {\n      on: { TOGGLE: 'active' }\n    },\n    active: {\n      on: { TOGGLE: 'inactive' }\n    }\n  }\n});\n\nexport const Toggler = () => {\n  const [state, send] = useMachine(toggleMachine);\n\n  return (\n    <button onClick={() => send('TOGGLE')}>\n      {state.value === 'inactive'\n        ? 'Click to activate'\n        : 'Active! Click to deactivate'}\n    </button>\n  );\n};\n```\n\n## Examples\n\n- [XState + React TodoMVC (CodeSandbox)](https://codesandbox.io/s/xstate-todomvc-33wr94qv1)\n\n## API\n\n### `useMachine(machine, options?)`\n\nA [React hook](https://reactjs.org/hooks) that interprets the given `machine` and starts a service that runs for the lifetime of the component.\n\n**Arguments**\n\n- `machine` - An [XState machine](https://xstate.js.org/docs/guides/machines.html) or a function that lazily returns a machine:\n\n  ```js\n  // existing machine\n  const [state, send] = useMachine(machine);\n\n  // lazily-created machine\n  const [state, send] = useMachine(() =>\n    createMachine({\n      /* ... */\n    })\n  );\n  ```\n\n- `options` (optional) - [Interpreter options](https://xstate.js.org/docs/guides/interpretation.html#options) and/or any of the following machine config options: `guards`, `actions`, `services`, `delays`, `immediate`, `context`, `state`.\n\n**Returns** a tuple of `[state, send, service]`:\n\n- `state` - Represents the current state of the machine as an XState `State` object.\n- `send` - A function that sends events to the running service.\n- `service` - The created service.\n\n### `useService(service)`\n\n::: warning Deprecated\n\nIn the next major version, `useService(service)` will be replaced with `useActor(service)`. Prefer using the `useActor(service)` hook for services instead, since services are also actors.\n\nAlso, keep in mind that only a single argument (the event object) can be sent to `send(eventObject)` from `useActor(...)`. When migrating to `useActor(...)`, refactor `send(...)` calls to use only a single event object:\n\n```diff\nconst [state, send] = useActor(service);\n-send('CLICK', { x: 0, y: 3 });\n+send({ type: 'CLICK', x: 0, y: 3 });\n```\n\n:::\n\nA [React hook](https://reactjs.org/hooks) that subscribes to state changes from an existing [service](https://xstate.js.org/docs/guides/interpretation.html).\n\n**Arguments**\n\n- `service` - An [XState service](https://xstate.js.org/docs/guides/interpretation.html).\n\n**Returns** a tuple of `[state, send]`:\n\n- `state` - Represents the current state of the service as an XState `State` object.\n- `send` - A function that sends events to the running service.\n\n### `useActor(actor, getSnapshot?)`\n\nA [React hook](https://reactjs.org/hooks) that subscribes to emitted changes from an existing [actor](https://xstate.js.org/docs/guides/actors.html).\n\n**Arguments**\n\n- `actor` - an actor-like object that contains `.send(...)` and `.subscribe(...)` methods.\n- `getSnapshot` - a function that should return the latest emitted value from the `actor`.\n  - Defaults to attempting to get the `actor.state`, or returning `undefined` if that does not exist.\n\n```js\nconst [state, send] = useActor(someSpawnedActor);\n\n// with custom actors\nconst [state, send] = useActor(customActor, (actor) => {\n  // implementation-specific pseudocode example:\n  return actor.getLastEmittedValue();\n});\n```\n\n### `useInterpret(machine, options?, observer?)`\n\nA React hook that returns the `service` created from the `machine` with the `options`, if specified. It also sets up a subscription to the `service` with the `observer`, if provided.\n\n_Since 1.3.0_\n\n**Arguments**\n\n- `machine` - An [XState machine](https://xstate.js.org/docs/guides/machines.html) or a function that lazily returns a machine.\n- `options` (optional) - [Interpreter options](https://xstate.js.org/docs/guides/interpretation.html#options) and/or any of the following machine config options: `guards`, `actions`, `services`, `delays`, `immediate`, `context`, `state`.\n- `observer` (optional) - an observer or listener that listens to state updates:\n  - an observer (e.g., `{ next: (state) => {/* ... */} }`)\n  - or a listener (e.g., `(state) => {/* ... */}`)\n\n```js\nimport { useInterpret } from '@xstate/react';\nimport { someMachine } from '../path/to/someMachine';\n\nconst App = () => {\n  const service = useInterpret(someMachine);\n\n  // ...\n};\n```\n\nWith options + listener:\n\n```js\n// ...\n\nconst App = () => {\n  const service = useInterpret(\n    someMachine,\n    {\n      actions: {\n        /* ... */\n      }\n    },\n    (state) => {\n      // subscribes to state changes\n      console.log(state);\n    }\n  );\n\n  // ...\n};\n```\n\n### `useSelector(actor, selector, compare?, getSnapshot?)`\n\nA React hook that returns the selected value from the snapshot of an `actor`, such as a service. This hook will only cause a rerender if the selected value changes, as determined by the optional `compare` function.\n\n_Since 1.3.0_\n\n**Arguments**\n\n- `actor` - a service or an actor-like object that contains `.send(...)` and `.subscribe(...)` methods.\n- `selector` - a function that takes in an actor's \"current state\" (snapshot) as an argument and returns the desired selected value.\n- `compare` (optional) - a function that determines if the current selected value is the same as the previous selected value.\n- `getSnapshot` (optional) - a function that should return the latest emitted value from the `actor`.\n  - Defaults to attempting to get the `actor.state`, or returning `undefined` if that does not exist. Will automatically pull the state from services.\n\n```js\nimport { useSelector } from '@xstate/react';\n\n// tip: optimize selectors by defining them externally when possible\nconst selectCount = (state) => state.context.count;\n\nconst App = ({ service }) => {\n  const count = useSelector(service, selectCount);\n\n  // ...\n};\n```\n\nWith `compare` function:\n\n```js\n// ...\n\nconst selectUser = (state) => state.context.user;\nconst compareUser = (prevUser, nextUser) => prevUser.id === nextUser.id;\n\nconst App = ({ service }) => {\n  const user = useSelector(service, selectUser, compareUser);\n\n  // ...\n};\n```\n\nWith `useInterpret(...)`:\n\n```js\nimport { useInterpret, useSelector } from '@xstate/react';\nimport { someMachine } from '../path/to/someMachine';\n\nconst selectCount = (state) => state.context.count;\n\nconst App = ({ service }) => {\n  const service = useInterpret(someMachine);\n  const count = useSelector(service, selectCount);\n\n  // ...\n};\n```\n\n### `asEffect(action)`\n\nEnsures that the `action` is executed as an effect in `useEffect`, rather than being immediately executed.\n\n**Arguments**\n\n- `action` - An action function (e.g., `(context, event) => { alert(context.message) })`)\n\n**Returns** a special action function that wraps the original so that `useMachine` knows to execute it in `useEffect`.\n\n**Example**\n\n```jsx\nconst machine = createMachine({\n  initial: 'focused',\n  states: {\n    focused: {\n      entry: 'focus'\n    }\n  }\n});\n\nconst Input = () => {\n  const inputRef = useRef(null);\n  const [state, send] = useMachine(machine, {\n    actions: {\n      focus: asEffect((context, event) => {\n        inputRef.current && inputRef.current.focus();\n      })\n    }\n  });\n\n  return <input ref={inputRef} />;\n};\n```\n\n### `asLayoutEffect(action)`\n\nEnsures that the `action` is executed as an effect in `useLayoutEffect`, rather than being immediately executed.\n\n**Arguments**\n\n- `action` - An action function (e.g., `(context, event) => { alert(context.message) })`)\n\n**Returns** a special action function that wraps the original so that `useMachine` knows to execute it in `useLayoutEffect`.\n\n### `useMachine(machine)` with `@xstate/fsm`\n\nA [React hook](https://reactjs.org/hooks) that interprets the given finite state `machine` from [`@xstate/fsm`] and starts a service that runs for the lifetime of the component.\n\nThis special `useMachine` hook is imported from `@xstate/react/fsm`\n\n**Arguments**\n\n- `machine` - An [XState finite state machine (FSM)](https://xstate.js.org/docs/packages/xstate-fsm/).\n- `options` - An optional `options` object.\n\n**Returns** a tuple of `[state, send, service]`:\n\n- `state` - Represents the current state of the machine as an `@xstate/fsm` `StateMachine.State` object.\n- `send` - A function that sends events to the running service.\n- `service` - The created `@xstate/fsm` service.\n\n**Example**\n\n```js\nimport { useEffect } from 'react';\nimport { useMachine } from '@xstate/react/fsm';\nimport { createMachine } from '@xstate/fsm';\n\nconst context = {\n  data: undefined\n};\nconst fetchMachine = createMachine({\n  id: 'fetch',\n  initial: 'idle',\n  context,\n  states: {\n    idle: {\n      on: { FETCH: 'loading' }\n    },\n    loading: {\n      entry: ['load'],\n      on: {\n        RESOLVE: {\n          target: 'success',\n          actions: assign({\n            data: (context, event) => event.data\n          })\n        }\n      }\n    },\n    success: {}\n  }\n});\n\nconst Fetcher = ({\n  onFetch = () => new Promise((res) => res('some data'))\n}) => {\n  const [state, send] = useMachine(fetchMachine, {\n    actions: {\n      load: () => {\n        onFetch().then((res) => {\n          send({ type: 'RESOLVE', data: res });\n        });\n      }\n    }\n  });\n\n  switch (state.value) {\n    case 'idle':\n      return <button onClick={(_) => send('FETCH')}>Fetch</button>;\n    case 'loading':\n      return <div>Loading...</div>;\n    case 'success':\n      return (\n        <div>\n          Success! Data: <div data-testid=\"data\">{state.context.data}</div>\n        </div>\n      );\n    default:\n      return null;\n  }\n};\n```\n\n## Configuring Machines\n\nExisting machines can be configured by passing the machine options as the 2nd argument of `useMachine(machine, options)`.\n\nExample: the `'fetchData'` service and `'notifySuccess'` action are both configurable:\n\n```js\nconst fetchMachine = createMachine({\n  id: 'fetch',\n  initial: 'idle',\n  context: {\n    data: undefined,\n    error: undefined\n  },\n  states: {\n    idle: {\n      on: { FETCH: 'loading' }\n    },\n    loading: {\n      invoke: {\n        src: 'fetchData',\n        onDone: {\n          target: 'success',\n          actions: assign({\n            data: (_, event) => event.data\n          })\n        },\n        onError: {\n          target: 'failure',\n          actions: assign({\n            error: (_, event) => event.data\n          })\n        }\n      }\n    },\n    success: {\n      entry: 'notifySuccess',\n      type: 'final'\n    },\n    failure: {\n      on: {\n        RETRY: 'loading'\n      }\n    }\n  }\n});\n\nconst Fetcher = ({ onResolve }) => {\n  const [state, send] = useMachine(fetchMachine, {\n    actions: {\n      notifySuccess: (ctx) => onResolve(ctx.data)\n    },\n    services: {\n      fetchData: (_, e) =>\n        fetch(`some/api/${e.query}`).then((res) => res.json())\n    }\n  });\n\n  switch (state.value) {\n    case 'idle':\n      return (\n        <button onClick={() => send('FETCH', { query: 'something' })}>\n          Search for something\n        </button>\n      );\n    case 'loading':\n      return <div>Searching...</div>;\n    case 'success':\n      return <div>Success! Data: {state.context.data}</div>;\n    case 'failure':\n      return (\n        <>\n          <p>{state.context.error.message}</p>\n          <button onClick={() => send('RETRY')}>Retry</button>\n        </>\n      );\n    default:\n      return null;\n  }\n};\n```\n\n## Matching States\n\nWhen using [hierarchical](https://xstate.js.org/docs/guides/hierarchical.html) and [parallel](https://xstate.js.org/docs/guides/parallel.html) machines, the state values will be objects, not strings. In this case, it is best to use [`state.matches(...)`](https://xstate.js.org/docs/guides/states.html#state-methods-and-getters).\n\nWe can do this with `if/else if/else` blocks:\n\n```js\n// ...\nif (state.matches('idle')) {\n  return /* ... */;\n} else if (state.matches({ loading: 'user' })) {\n  return /* ... */;\n} else if (state.matches({ loading: 'friends' })) {\n  return /* ... */;\n} else {\n  return null;\n}\n```\n\nWe can also continue to use `switch`, but we must make an adjustment to our approach. By setting the expression of the `switch` to `true`, we can use [`state.matches(...)`](https://xstate.js.org/docs/guides/states.html#state-methods-and-getters) as a predicate in each `case`:\n\n```js\nswitch (true) {\n  case state.matches('idle'):\n    return /* ... */;\n  case state.matches({ loading: 'user' }):\n    return /* ... */;\n  case state.matches({ loading: 'friends' }):\n    return /* ... */;\n  default:\n    return null;\n}\n```\n\nA ternary statement can also be considered, especially within rendered JSX:\n\n```jsx\nconst Loader = () => {\n  const [state, send] = useMachine(/* ... */);\n\n  return (\n    <div>\n      {state.matches('idle') ? (\n        <Loader.Idle />\n      ) : state.matches({ loading: 'user' }) ? (\n        <Loader.LoadingUser />\n      ) : state.matches({ loading: 'friends' }) ? (\n        <Loader.LoadingFriends />\n      ) : null}\n    </div>\n  );\n};\n```\n\n## Persisted and Rehydrated State\n\nYou can persist and rehydrate state with `useMachine(...)` via `options.state`:\n\n```js\n// ...\n\n// Get the persisted state config object from somewhere, e.g. localStorage\nconst persistedState = JSON.parse(localStorage.getItem('some-persisted-state-key')) || someMachine.initialState;\n\nconst App = () => {\n  const [state, send] = useMachine(someMachine, {\n    state: persistedState // provide persisted state config object here\n  });\n\n  // state will initially be that persisted state, not the machine's initialState\n\n  return (/* ... */)\n}\n```\n\n## Services\n\nThe `service` created in `useMachine(machine)` can be referenced as the third returned value:\n\n```js\n//                  vvvvvvv\nconst [state, send, service] = useMachine(someMachine);\n```\n\nYou can subscribe to that service's state changes with the [`useEffect` hook](https://reactjs.org/docs/hooks-effect.html):\n\n```js\n// ...\n\nuseEffect(() => {\n  const subscription = service.subscribe((state) => {\n    // simple state logging\n    console.log(state);\n  });\n\n  return subscription.unsubscribe;\n}, [service]); // note: service should never change\n```\n\n## Migration from 0.x\n\n- For spawned actors created using `invoke` or `spawn(...)`, use the `useActor()` hook instead of `useService()`:\n\n  ```diff\n  -import { useService } from '@xstate/react';\n  +import { useActor } from '@xstate/react';\n\n  -const [state, send] = useService(someActor);\n  +const [state, send] = useActor(someActor);\n  ```\n\n## Resources\n\n[State Machines in React](https://gedd.ski/post/state-machines-in-react/)\n","readmeFilename":"README.md","_id":"@xstate/react@2.0.0-pr2674-20219612435","_nodeVersion":"12.20.0","_npmVersion":"7.1.0","dist":{"integrity":"sha512-dIGEjdn0TKvJdLcGDpPITgfC2GNMp4k/3fFUH0oS5VbPy7WDSm2AagY/B1O+rF2xjadhV86okz47d0dUAHCLxw==","shasum":"8750d167934e01573240e33767b8fe5f08df16fa","tarball":"http://registry-npm.ywwl.com/@xstate/react/download/@xstate/react-2.0.0-pr2674-20219612435.tgz","fileCount":56,"unpackedSize":113249,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFUzi7rxHUld1Qt8WQkOfoDkYxIHco6OOipTkRrK0rcbAiAT7UTqa5gvhe2vK5K7A4mCY7hEsTMs8Bm15X/z3bC79w=="}],"size":23461,"noattachment":false,"key":"/@xstate/react/-/@xstate/react-2.0.0-pr2674-20219612435.tgz"},"_npmUser":{"name":"andarist","email":"mateuszburzynski@gmail.com"},"maintainers":[{"name":"andarist","email":"mateuszburzynski@gmail.com"},{"name":"davidkpiano","email":"davidkpiano@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/react_2.0.0-pr2674-20219612435_1633522747981_0.9093873386597096"},"_hasShrinkwrap":false,"publish_time":1633522748165,"_cnpm_publish_time":1633522748165,"dist-tags":{"alpha":"7.0.0-alpha.7","beta":"7.0.0-beta.0","latest":"6.1.0"}}