UNPKG

xstate-helpers

Version:

A collection of helpers for XState (with React).

56 lines (46 loc) • 1.81 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var react = require('@xstate/react'); function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefault(React); function createReactContextHelpers( /** * Display name for the react context */ displayName, /** * Function that provides the interpreter for your machine. * * Inside it you should use `useInterpret()` from `@xstate/react`. You can pass options to it as normal * * Example: * */ getInterpreter) { const machineServiceContext = /*#__PURE__*/React__default["default"].createContext(null); machineServiceContext.displayName = displayName; return { ReactContext: machineServiceContext, Provider: function (props) { const interpreter = typeof getInterpreter === 'function' ? getInterpreter(props) : getInterpreter; return /*#__PURE__*/React__default["default"].createElement(machineServiceContext.Provider, { value: interpreter }, typeof props.children == 'function' ? props.children({ interpreter }) : props.children); }, useInterpreter, useSelector: (selector, compare) => react.useSelector(useInterpreter(), selector, compare), useActor: () => react.useActor(useInterpreter()), useSend: () => useInterpreter().send }; ////////////////////////////// function useInterpreter() { const service = React__default["default"].useContext(machineServiceContext); if (!service) { throw new Error(`Machine interpreter ${displayName} is not available, make sure you use are calling this function as a child of the machine provider.`); } return service; } } exports.createReactContextHelpers = createReactContextHelpers;