Skip to content

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

Closed
@kempha

Description

@kempha

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions