LoginSignup
4
0

More than 1 year has passed since last update.

【livewire】プロパティにnull許容型の型を使用する際の注意点

Last updated at Posted at 2022-12-21

概要

null許容string型で定義した際に

  • mount()内で初期化
  • nullを入れる
  • 値がnullのままリクエストが走る

条件を満たすと未初期化エラーが発生する。

再現

こんな感じにnull許容型のstring型を定義します

php
class Index extends Component
{
    public ?string $text;

    public function mount()
    {
        $this->text = null;
    }

    public function hoge()
    {
        dd($this->text);
    }
.....
}
blade
<button wire:click="hoge()">aaa</button>

aaaボタンをクリックすると

Error
Typed property App\Http\Livewire\Top\Index::$text must not be accessed before initialization

とエラーが出ます。

先に対処

初期化はプロパティの宣言時にやりましょう

php
class Index extends Component
{
+   public ?string $text = null;

    public function mount()
    {
    }

    public function hoge()
    {
        dd($this->text);
    }
.....
}

なんでや?

リクエスト発生時、恐らく

  1. クラスのプロパティ初期化
  2. フロントから受け取った値を代入する

はずで、

livewireさんは初期化処理を勝手にやってくれる....はずなんですが
その際に値がnullだったら初期化の際に値を入れてくれない
んですよね、恐らく。
バグなのやら仕様なのやら

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0