ux icon indicating copy to clipboard operation
ux copied to clipboard

[Live Component] Typed property must not be accessed before initialization

Open kempha opened this issue 1 year ago • 1 comments

There is this live component:

#[AsLiveComponent]
final class TestComponent
{
    use DefaultActionTrait;

    #[LiveProp(writable: true, onUpdated: 'onNameUpdated')]
    public string $name;

    #[LiveProp(writable: true)]
    public string $phone;

    #[PostMount]
    public function postMount(): void
    {
        $this->name = 'kempha';
        $this->phone = '1234567890';
    }

    public function onNameUpdated(): void
    {
        $phone = $this->phone; // Error: Typed property must not be accessed before initialization.
    }
}

I can't access the phone inside the onNameUpdated() handler because it hasn't been initialized yet. This happens because the handler is called as soon as the variable to which the handler refers is initialized. But other class variables have not yet been initialized during hydration.

I believe that all handlers should be called after all class variables have been initialized during component hydration. The problem is here: Symfony\UX\LiveComponent\LiveComponentHydrator::hydrate() line 218. The onUpdated handler is called directly inside the iteration when the variable associated with it has been initialized. All handlers should be called outside the foreach(), after all variables have been initialized.

kempha avatar Jul 02 '24 07:07 kempha

Hey @kempha !

That's an intersting idea... would you be ok to start some PR / digging on this ? :)

smnandre avatar Jul 03 '24 20:07 smnandre

would you be ok to start some PR / digging on this ? :)

I can make a pull request. It will become clear how I see it)

kempha avatar Jul 10 '24 06:07 kempha

That'd be nice! Thank you :)

smnandre avatar Jul 10 '24 07:07 smnandre