xstate-helpers
Version:
A collection of helpers for XState (with React).
48 lines (42 loc) • 1.51 kB
JavaScript
import React from 'react';
import { useSelector, useActor } from '@xstate/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.createContext(null);
machineServiceContext.displayName = displayName;
return {
ReactContext: machineServiceContext,
Provider: function (props) {
const interpreter = typeof getInterpreter === 'function' ? getInterpreter(props) : getInterpreter;
return /*#__PURE__*/React.createElement(machineServiceContext.Provider, {
value: interpreter
}, typeof props.children == 'function' ? props.children({
interpreter
}) : props.children);
},
useInterpreter,
useSelector: (selector, compare) => useSelector(useInterpreter(), selector, compare),
useActor: () => useActor(useInterpreter()),
useSend: () => useInterpreter().send
}; //////////////////////////////
function useInterpreter() {
const service = React.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;
}
}
export { createReactContextHelpers };