#How to import an assign action to use in setup()

1 messages · Page 1 of 1 (latest)

rancid sandal
#

Having this code:

import { assign, setup } from "xstate"

const increase = assign({
counter: ({ context }) => context.counter + 1,
})

const counterMachine = setup({
types: {
context: {} as {
counter: number
},
},
actions: {
increase,
},
}).createMachine({
context: {
counter: 0,
},
entry: { type: "increase" },
})

Why is typescript yelling at me (hovering over increase) and saying: "Types of property '_out_TActor' are incompatible. Type 'ProvidedActor | undefined' is not assignable to type '{ src: string; logic: UnknownActorLogic; id: string | undefined; } | undefined'. Type 'ProvidedActor' is not assignable to type '{ src: string; logic: UnknownActorLogic; id: string | undefined; }'. Property 'id' is optional in type 'ProvidedActor' but required in type '{ src: string; logic: UnknownActorLogic; id: string | undefined; }'.ts(2322)"

Is there a good practice to import an action here and not having typescript yelling?

Thanks for your good work 🙂

sage token
#

cc. @glacial crag (I've seen that _out_TActor randomly before too - is it still necessary?)

glacial crag
#

we couldn't infer spawn within assign without it

gilded pendant
# glacial crag just move it "inline" into the `setup`: https://www.typescriptlang.org/play?#cod...

@glacial crag what about this use case 👇

Ideally I'd like to make the actions passed through provide typed and inferrable within the createMemeMachine

export default function CreateMeme(props: Props) {
  //...an animation hook
  const [promptAnimation, promptAnimationAPI] = useSpring(() => ({ config: LINEAR_SPRING }));

  const [state, send] = useMachine(
    createMemeMachine.provide({
      actions: {
        animatePromptReveal: () => {
          // uses a hook
          promptAnimationAPI.start({...});
        },
      },
    })
  );

  // return the React component
  return (
   ...
  )
}
gilded pendant
#

@sage token if this isn't possible, it would be nice to have some of the actions be typed in setup, and then to be able to optionally extend those actions with provide without getting type errors

glacial crag
#

@gilded pendant please share this in a form of TS playground or something. I can't even quickly see here where you get type errors here etc.

gilded pendant
# glacial crag <@950913934217596958> please share this in a form of TS playground or something....

I just simplified the example ☝️

The scenario/use case is that I have some localized react hook that can be triggered when a machine state is hit. The action requires a reference to this hook, and it would be nice if there was some way to type some of the provided actions. Currently, I either have to stick all actions in provide, or all actions in setup. If I have half and half, the actions in provide throw a type error.

#

The other solution is to just stuff all of the references to these hooks into the machine's context - but that feels...messy?