{"name":"@xstate/react","version":"1.0.0-rc.0","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","prebuild":"npm run clean","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/jest":"^24.0.11","@types/jsdom":"^12.2.3","@types/react":"^16.9.0","@types/react-dom":"^16.8.5","@xstate/fsm":"^1.0.3","jest":"^24.8.0","jsdom":"^14.0.0","jsdom-global":"^3.0.2","lerna-alias":"3.0.3-0","react":"^16.9.0","react-dom":"^16.9.0","ts-jest":"^24.0.2","typescript":"^3.6.2","xstate":"^4.7.0-rc6"},"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.0","_nodeVersion":"10.15.3","_npmVersion":"6.12.1","dist":{"integrity":"sha512-jUS/eAWTzp9rnIJck/Sz3Xl4dFvYrtB+DcOoe6NF7OM7eFxO152Ba3zbbzbGSUA9Fqf4jAT5oOKcFqs28Pp9kA==","shasum":"244e794c871f2e85d8286b08687e4e37738ec7e4","tarball":"http://registry-npm.ywwl.com/@xstate/react/download/@xstate/react-1.0.0-rc.0.tgz","fileCount":9,"unpackedSize":19817,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdy1U9CRA9TVsSAnZWagAAXcIP/3AQPDqH8iUyy1Ujk/Zj\njbfsDr6LyN1Ca1o8JINW/gsl+NownMCP0he7ORLxlWNukFx/YNI8U87Ccv01\n3HDVLAkzp07xGJlnH0K+ZjZGdLV7ZwMf3OwKISxx3VPlFKc3rZggjagL8r7L\nbyZUnnE6oMO4R+bT9XzZZdmKGv6o6R6HJHFY0bTlrVdKjOyFQyw0s7FP93Hl\nBg/oPC6o5u5aGiXSaSfu3rVwrHVwF9GFYF/Scg3z5HbMdpeQ5IqiGeg7laB+\nsnZlj7GmpXL4rQJWi1tUJXceQTbi6sSa/zUzoP/GwdagboWUOwWp7RsNm/L9\nXHx+6dHVIhv7LZH6pfaXhPVp3a2HofO8uaUo/maL9oHSp+7WkSoos/lep8By\nbln0j4WvT/3MJMQ2ie6WRJzrB/NofCaQfr3SUdmU+BD/rhHBqk8L/memRC2M\nSgjMVDEYGH/ISvG1J3l+bdvIsYqSleOx7qtxKu/Zf76owt7WtyDMStgIuOvL\nmUXiixY5ckWZLguyPTn8XHaKcUhQBzEoXiONkpBncpvJNDwbKBGGY6JdMhbV\nnofel5UvpTpP6PXc+T4uIW2MnPngU8DrLPqjbXqYfJl5SJoiSLLrJCCjujaA\nvgWze2BHxGxItuc5qDGftfVqVQjl28JEma6aYhjr0fCU0Ng+l+i2sNOQgZkg\nr7n3\r\n=cX3p\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCrlWNO67hAlS83uobdC51CQfjTaPKlx3Pkc3T/n4R9rQIhALVUKE7Q9xgx0va9asQAHb+5QVbXJnhR3SnUHMBsn5+Z"}],"size":5943,"noattachment":false,"key":"/@xstate/react/-/@xstate/react-1.0.0-rc.0.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.0_1573606716603_0.07589260776722151"},"_hasShrinkwrap":false,"publish_time":1573606716701,"_cnpm_publish_time":1573606716701,"dist-tags":{"alpha":"7.0.0-alpha.7","beta":"7.0.0-beta.0","latest":"6.1.0"}}