statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
27.21k stars 1.26k forks source link

Bug: sendParent throws an error when no parent exists #5120

Open dhensby opened 1 week ago

dhensby commented 1 week ago

XState version

XState version 5

Description

The docs for sendParent() state (emphasis added):

The sendParent(...) action is a special action that sends an event to the parent actor, if it exists.

However, when running sendParent() as an action an error is thrown (Error: Unable to send event to actor '#_parent' from machine '(machine)'.).

Code to reproduce:

import { createActor, sendParent, setup } from 'xstate';

const machine = setup({}).createMachine({
    initial: 'init',
    states: {
        init: {
            entry: sendParent(() => ({ type: 'init' })),
        },
    },
});

const actor = createActor(machine);
actor.start();

Expected result

I expect that no error is thrown and the sendParent() action becomes a no op when no parent exists.

Actual result

The following error is thrown: Error: Unable to send event to actor '#_parent' from machine '(machine)'.

Reproduction

see description

Additional context

Reproduced with xstate@5.18.2

davidkpiano commented 1 week ago

This is currently by design - it is a breaking change to change this to a warning instead of an error currently 🤔

dhensby commented 1 week ago

Fair enough - I suppose this is more a docs issue, then?

Is there a way to nicely achieve this (optional send to parent)? Or maybe the options sent to the sendParent could have a new property to allow it to be optional? eg: sendParent(() => ({ type: 'init' }), { allowMissingParent: true })