Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide convenience type InterpreterFrom<typeof machine> #2102

Merged
merged 3 commits into from Apr 16, 2021

Conversation

VanTanev
Copy link
Contributor

Add the convenience type

export type InterpreterFrom<
  T extends StateMachine<any, any, any, any>
> = T extends StateMachine<
  infer TContext,
  infer TStateSchema,
  infer TEvent,
  infer TTypestate
>
  ? Interpreter<TContext, TStateSchema, TEvent, TTypestate>
  : never;

This is useful in the following pattern:

import React from 'react'
import { createMachine, InterpreterFrom } from 'xstate'
import { useService } from '@xstate/react'

const machine = createMachine(...)
type MachineService = InterpreterFrom<typeof machine>

const MachineServiceContext = React.createContext<MachineService>(null!)
const useMachineService = (): MachineService  => {
  const service = React.useContext(MachineServiceContext)
  if (!service) throw new Error(`You must call useMachineService in a child component of <MachineProvider>`)
  return service
}
const MachineProvider: React.FC = ({ children }) => {
  const service = useInterpret(machine)
  return <MachineServiceContext.Provider value={service}>{children}</MachineServiceContext.Provider>
}

const App = () => {
  return <MachineProvider><Compontent /></MachineProvider>
}
const Component = () => {
  const service = useMachineService()
  const [state, send] = useService(service)
  // ...
}

This is a companion type to ActorRefFrom<T>.

@changeset-bot
Copy link

changeset-bot bot commented Apr 15, 2021

🦋 Changeset detected

Latest commit: 25d93b5

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
xstate Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
@davidkpiano davidkpiano merged commit 7eaad96 into statelyai:master Apr 16, 2021
@github-actions github-actions bot mentioned this pull request Apr 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants