{"name":"@xstate/react","version":"1.0.0-rc.1","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","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":{"react":"^16.8.0","xstate":"^4.7.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.7.2","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 [current, send] = useMachine(toggleMachine);\n\n  return (\n    <button onClick={() => send('TOGGLE')}>\n      {current.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 `[current, send, service]`:\n\n- `current` - 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 `[current, send]`:\n\n- `current` - 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)` <Badge text=\"0.8+\"/>\n\nA [React hook](https://reactjs.org/hooks) that subscribes to messages (events) from actors, and can send messages (events) to actors.\n\n**Arguments**\n\n- `actor` - An actor-like object, which has `.subscribe(listener)` and `.send(event)` methods.\n\n**Returns** a tuple of `[current, send]`:\n\n- `current` - Represents the current message sent from the actor.\n- `send` - A function that sends events to the actor.\n\n### `useMachine(machine)` with `@xstate/fsm` <Badge text=\"1.1+\"/>\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\n**Returns** a tuple of `[current, send, service]`:\n\n- `current` - 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 [current, send] = useMachine(fetchMachine);\n\n  useEffect(() => {\n    current.actions.forEach(action => {\n      if (action.type === 'load') {\n        onFetch().then(res => {\n          send({ type: 'RESOLVE', data: res });\n        });\n      }\n    });\n  }, [current]);\n\n  switch (current.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\">{current.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 [current, send] = useMachine(fetchMachine, {\n    actions: {\n      notifySuccess: ctx => onResolve(ctx.data)\n    },\n    services: {\n      fetchData: (_, e) => fetch(`some/api/${e.query}`).then(res => res.json())\n    }\n  });\n\n  switch (current.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: {current.context.data}</div>;\n    case 'failure':\n      return (\n        <>\n          <p>{current.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\nUsing a `switch` statement might suffice for a simple, non-hierarchical state machine, but for [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's better to use [`state.matches(...)`](https://xstate.js.org/docs/guides/states.html#state-methods-and-getters):\n\n```js\n// ...\nif (current.matches('idle')) {\n  return /* ... */;\n} else if (current.matches({ loading: 'user' })) {\n  return /* ... */;\n} else if (current.matches({ loading: 'friends' })) {\n  return /* ... */;\n} else {\n  return null;\n}\n```\n\nA ternary statement can also be considered, especially within rendered JSX:\n\n```jsx\nconst Loader = () => {\n  const [current, send] = useMachine(/* ... */);\n\n  return (\n    <div>\n      {current.matches('idle') ? (\n        <Loader.Idle />\n      ) : current.matches({ loading: 'user' }) ? (\n        <Loader.LoadingUser />\n      ) : current.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 [current, send] = useMachine(someMachine, {\n    state: persistedState // provide persisted state config object here\n  });\n\n  // current will initially be that persisted state, not the machine's initialState\n\n  return (/* ... */)\n}\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.1","_nodeVersion":"12.4.0","_npmVersion":"6.13.1","dist":{"integrity":"sha512-GBIgGlotgZO7kG0BnjnzYK7npSrcmCSFJLfedt3AGONrFGpLh17CJdm1d6yUbPLwFkL8rQD94ovW8gIBGkZULg==","shasum":"efff3b4097f45d8c24c9402ad091a61a843b034d","tarball":"http://registry-npm.ywwl.com/@xstate/react/download/@xstate/react-1.0.0-rc.1.tgz","fileCount":9,"unpackedSize":19864,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeAUk7CRA9TVsSAnZWagAAkNIP/jvFy6PwuSqW1/DrBYbu\nfYUpFeG5H6GP1nVHi16xWBKO9wf+SEczMd13EVHvBSQVSR5XXnwMeWIJUi8N\nFlZS1RA7MvsmY6CBREVDzGO/SkeqGaEcUDRcFjyj+WDOAytlo7QRo1X4z1BK\nRLaukAEPbfURSA/dM4GAD825ZRCwzlAicx8beW9muGggiB6hdHDX3MGaZ1gd\ndH7kvEW6re0igaycuJRH8CtjrBjFroy75F+El2gWxFDCTvzIfbek/EgkHEZ6\n76uCnyAv1Y7WyuCknUft6uhlXeqkbJVG+QlpHrJabcSGb0WzKcsV8FvST+U3\nPMVwIIpy+DzdLOrP1bugY1J7R08oGwQGOinE7bQqKtBWdf138hGI1XFpSQOk\nE9mBHiZpODDcSCrYJDohc2h05MJJ4IoN2O+5DzzY/BbQOxPNxyxAot5I+dny\nxatmWQWkVwVt+rwg+9QXmRhsNneAH+nJdmU1PoPrK2q9uyg7p9PR7nPTcsrM\nHU9GYm54YaRKrA9D4nvJBRSqbELM/xV5WCKYtiGCqj08Q9/R81otRSLujCh+\n8KIxq8f7wJ7QmYaM1hkoW1n6AXxNvmiM94XGCC737xmMhlEIEI625U/VsWZx\nw6nGkGsOhMNe7GRUpU8dG2kJMTxd3Z6z1OlQTdYkoF7DtdM1Q2DMCA0RcjwC\nxIUk\r\n=ZMrv\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFHFAj+tKEk3kH+xtMTu0L5D083TgoCoxunPXCJmZgxGAiEAnAvxRontG1erb566Qe/N846gantbIueB9jrePeApUvk="}],"size":5963,"noattachment":false,"key":"/@xstate/react/-/@xstate/react-1.0.0-rc.1.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.1_1577142587384_0.5625062448240252"},"_hasShrinkwrap":false,"publish_time":1577142587529,"_cnpm_publish_time":1577142587529,"dist-tags":{"alpha":"7.0.0-alpha.7","beta":"7.0.0-beta.0","latest":"6.1.0"}}