xstate: Bug: Unable to type `sendBack` in `fromCallback`

XState version

XState version 5

Description

Currently, the fromCallback function takes two generics, the event type for receive and the input type but the sendBack generic type isn’t exposed.

Currently, the only way to get around this is to do the following:

import type { InvokeCallback } from 'xstate/dist/declarations/src/actors/callback';

fromCallback((({ receive, sendBack, input }) => {
   // ...
}) as InvokeCallback<ReceiveEvent, SendBackEvent, InputEvent>);

Expected result

fromCallback should have a 3rd generic parameter for the sendBack event type.

Actual result

fromCallback does not have a 3rd generic parameter for the sendBack event type.

Reproduction

N/A

Additional context

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 2
  • Comments: 15 (1 by maintainers)

Most upvoted comments

Should be released soon 🚢

I am using XState 5.18 and this works:

import {
	fromCallback,
	type AnyEventObject,
	type CallbackLogicFunction,
	type EventObject,
	type NonReducibleUnknown
} from 'xstate';

export function enhancedFromCallback<
	TReceive extends EventObject = AnyEventObject,
	TSendBack extends EventObject = AnyEventObject,
	TInput = NonReducibleUnknown,
	TEmitted extends EventObject = EventObject
>(callback: CallbackLogicFunction<TReceive, TSendBack, TInput, TEmitted>) {
	return fromCallback(callback);
}

Thanks for your solution @phcoliveira 🥇. @Andarist is your team planing to cover this issue anytime soon?

Ah interesting! Apparently it’s not released yet. 5.17.4 is the latest on npm, and there’s still InvokeCallback but no CallbackLogicFunction yet. Merged 4 days ago - let’s see and wait.

And Outch! 5.17.4 still has the InvokeCallback - but it’s not exported anymore 😆 I’ll roll back for now…

This makes think about how a child actor’s events are perceived by the parent actor. I believe they are not “perceived” at all. Not in the sense of knowing its defined interface.

I find strange that the events sent by a child are handled like this:

const someCallback = fromCallback();

const parent = createMachine({
  id: 'parent',
  states: {
    active: {
      on: {
        'event.from.child': {
          actions: ['someAction']
        },
      },
      invoke: {
        id: 'child',
        src: someCallback
      }
    }
});

Because of this, the parent machine has to type itself the event event.from.child, as if it should know about it to redefine it.

I believe the events sent from a child could be handled just like the events onDone and onError, used for promises.

const someCallback = fromCallback();

const parent = createMachine({
  id: 'parent',
  states: {
    active: {
      on: {
        'parent.is.taking.over': {
          target: 'inactive'
        },
      },
      invoke: {
        id: 'child',
        src: someCallback
        // onDone: for promises, properly typed
        // onError: for promises
        on: {
          'event.from.child': { // type inferred from someCallback
            actions: sendTo('parent', ({event}) => ({
              ...event // work with properties if needed
              type: 'parent.is.taking.over'
            })
          },
        },
      }
    }
});

In this way, I believe the “contract” between parent and child is clearer.

I did a different hack.

import {fromCallback} from 'xstate';
import type {AnyEventObject, EventObject, NonReducibleUnknown} from 'xstate';
import type {InvokeCallback} from 'xstate/dist/declarations/src/actors/callback';

export function enhancedFromCallback<
	TReceive extends EventObject = AnyEventObject,
	TSend extends EventObject = AnyEventObject,
	TInput = NonReducibleUnknown
>(invokeCallback: InvokeCallback<TReceive, TSend, TInput>) {
	return fromCallback(invokeCallback);
}

It seems to work fine.

import {onValue} from 'firebase/database';
import type {Query} from 'firebase/database';

import {enhancedFromCallback, NoEventError} from '$lib';
import type {DatabaseKey} from '$lib';

export type TReceive =
	| {type: 'database.subscribe'; data: {query: Query}}
	| {type: 'database.unsubscribe'};

export type TSend =
	| {type: 'database.value'; data: {key: DatabaseKey; value: unknown}}
	| {type: 'database.empty'};

export const databaseSubscription = enhancedFromCallback<TReceive, TSend>(({sendBack, receive}) => {
	let unsubscribe: ReturnType<typeof onValue> | undefined;

	receive((event) => {
		switch (event.type) {
			case 'database.subscribe': {
				unsubscribe?.();

				unsubscribe = onValue(event.data.query, (snapshot) => {
					if (snapshot.exists()) {
						sendBack({
							type: 'database.value',
							data: {key: snapshot.key!, value: snapshot.val()},
						});
					} else {
						sendBack({type: 'database.empty'});
					}
				});

				break;
			}
			case 'database.unsubscribe': {
				unsubscribe?.();
				break;
			}
			default: {
				// Sentry
				// @ts-expect-error. It should never happen, as no other event should be sent.
				throw new NoEventError(event.type);
			}
		}
	});

	return () => unsubscribe?.();
});