{"name":"@xstate/react","version":"1.0.0-rc.5","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/master/packages/xstate-react#readme","license":"MIT","main":"lib/index.js","types":"lib/index.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","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","xstate":"^4.7.0"},"peerDependenciesMeta":{"@xstate/fsm":{"optional":true},"xstate":{"optional":true}},"dependencies":{"use-isomorphic-layout-effect":"^1.0.0","use-subscription":"^1.3.0"},"devDependencies":{"@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":"^24.8.0","jsdom":"^14.0.0","jsdom-global":"^3.0.2","lerna-alias":"3.0.3-0","react":"^16.12.0","react-dom":"^16.12.0","ts-jest":"^24.1.9","typescript":"^3.8.3","xstate":"*"},"readme":"# @xstate/react\n\n## Quick Start\n\n1. Install `xstate` and `@xstate/react`:\n\n```bash\nnpm i xstate @xstate/react\n```\n\n2. Import the `useMachine` hook:\n\n```js\nimport { useMachine } from '@xstate/react';\nimport { Machine } from 'xstate';\n\nconst toggleMachine = Machine({\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## 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).\n- `options` (optional) - [Interpreter options](https://xstate.js.org/docs/guides/interpretation.html#options) OR one of the following Machine Config options: `guards`, `actions`, `activities`, `services`, `delays`, `immediate`, `context`, or `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\nA [React hook](https://reactjs.org/hooks) that subscribes to state changes from an existing [service](TODO).\n\n**Arguments**\n\n- `service` - An [XState service](https://xstate.js.org/docs/guides/communication.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### `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/lib/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/lib/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 = ({ onFetch = () => new Promise(res => res('some data')) }) => {\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 <Badge text=\"0.7+\"/>\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 = Machine({\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'));\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## Resources\n\n[State Machines in React](https://gedd.ski/post/state-machines-in-react/)\n","readmeFilename":"README.md","_id":"@xstate/react@1.0.0-rc.5","_nodeVersion":"13.5.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-5PdMp4iY5ANNQlUeh0wo3pZ/w7ZfKGoz9E0mK/q3AqkDK+kSQc+5tKnbsmun0qHxdFCS7tyU8/ys2roQ09Ei3A==","shasum":"3d5b7c41fa562357651ae937717359b64c56f047","tarball":"http://registry-npm.ywwl.com/@xstate/react/download/@xstate/react-1.0.0-rc.5.tgz","fileCount":19,"unpackedSize":34513,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJe+/MuCRA9TVsSAnZWagAAcgQP/3gosHKzRMrG1mzjvyY2\n5JcW1kPHJyQdvsF9QhJ7xShLn/Vf24MsRjBUg2X+NKJLTejrjU2GHgpTkDSC\nNmzG3VeBeMYIWEyfPjc8K4Alw5Sr7ir0vXxWenUTJN6rM7GTNSe0EAcOb6Wm\nviKLpKnTCFWeaHt9M/h/1sBluvPHOEmWfWpuKBFixGHl3Al97i055e9HnPyc\nkornUXhDp9rBbZMYz5kt2k2+kUmIKAvpfILdpgIO3bciqA1beTAwhMXe29Rk\nsRonChT0u/nyoqGoCoPIWScHwXSHd83Gw4VG58UjD8tpHrR12gVxzwLo36/u\nav1Sjogq/1zeu10glWTHKuOsR5rJgMny8dEl5JGupyLEPb3U7fbXz9AQSlEW\n77vIPLWhVL1TkSZhlQC82S/mHEVn/M0xcaCJTA/6ab+verstiwYeAvWrZ71p\nLQdZ+tDT7e5dhvKCJwq2k/vANi2sfEWpa1XI7LltJW+bAPds9mIKgWg9XLC0\nDx8JoGGVsd0z/bwanTyeTFWC5FfhHt2XJT1oZ1MnXjz8p3ZONOGXixQApAT/\ndAYZQOIZf+Q2OesrHXamgv1E4Ti1EdAPgR3bSfQQHOCPfTPUqVZ0wlXfq1ja\nZRo2BtFrdZY8Co34CGsi0tzLqIwyuWOYKtd7CUqIN5MNeNzNFlZ4JTqwjv/m\ngjZu\r\n=lyJd\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDKl/gZ1XWsEWrX4fhDg0fyVpPGSLgD+DHNmEgoUL8FWQIgO0WabEP3fqzAdtCwxbOJuejoVkqHoWbxVbgB8lcJ1b0="}],"size":9153,"noattachment":false,"key":"/@xstate/react/-/@xstate/react-1.0.0-rc.5.tgz"},"maintainers":[{"name":"davidkpiano","email":"davidkpiano@gmail.com"}],"_npmUser":{"name":"davidkpiano","email":"davidkpiano@gmail.com"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/react_1.0.0-rc.5_1593570094388_0.6831937258917544"},"_hasShrinkwrap":false,"publish_time":1593570094492,"_cnpm_publish_time":1593570094492,"dist-tags":{"alpha":"7.0.0-alpha.7","beta":"7.0.0-beta.0","latest":"6.1.0"}}