-
Main questionHi, is there a helper function that I can use to get a type (let's call it example: const [state] = useMachine(MyMachine, {})
const checkStateAndDoSomething = (expectedState: MagicType) => {
if (state.matches(expectedState)) { // <-- Error because MagicType doesn't satisfy what the matches function expects
// Do stuff...
}
} I imagine it would be something like Side questionAlso, I'd like to hear opinions on whether what I'm building makes sense or if there's a better approach: I'm building a React HOC to conditionally render a component based on the current state of my machine The HOC function takes two parameters, the component to wrap and a export const withMyMachine = (Component: React.FC, matchingState: string /* I need a special type here */) => {
return (props: Record<string, unknown>) => {
const [state] = MyMachineContext.useActor();
// If matchingState is the current state, render the component
if (state.matches(matchingState)) { // <--- type error here since string is not constrained enough
return <Component {...props} />;
}
// If not, do not render it
return null;
};
}; An example of how this would be used:
// Imagine MyMachine has possible states: state1, state2, state3 and state4
export const ParentComponent = () => {
return (
<MyMachineContext.Provider>
{/* Build one component for each possible state of MyMachine, call them all but only the one that corresponds to the current state will be rendered */}
<ComponentForState1 />
<ComponentForState2 />
<ComponentForState3 />
<ComponentForState4 />
</MyMachineContext.Provider>
);
};
const ComponentForState1 = () => {
// Do stuff and call actions relevant to state1
// This code will only get called when current state = state1 thanks to the HOC
};
export default withMyMachine(ComponentForState1, 'state1'); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
If anyone's needing this, I ended up using one of the properties from the typegen: export type MyMachineState = import('./machine.typegen').Typegen0['matchesStates']; |
Beta Was this translation helpful? Give feedback.
If anyone's needing this, I ended up using one of the properties from the typegen: