-1

I have a LiveComponent with an array of prices, depending on if a checkbox is checked or not the prices should be with VAT in- or excluded.

This works nicely. The problem is:

  • When I check the box -> the prices are updated with VAT included (as expected).
  • I refresh the page
  • The box is still checked (as expected) -> but the prices are not with VAT anymore.

So the LiveComponent saves the state of the checkbox, but does not trigger the correct action after refresh depending on the state.

I thought I could fix it by using #[PreReRender].

<?php


#[AsLiveComponent]
class MyLiveComponent
{
    use DefaultActionTrait;
    use ComponentWithFormTrait;
    use ComponentToolsTrait;

    public function __construct(
      
    )
    {
    }

    #[LiveProp(hydrateWith: 'hydratePricings', dehydrateWith: 'dehydratePricings')]
    public array $pricings = [];

  
    #[LiveProp]
    public bool $inclVat = false;


    #[LiveAction]
    public function toggleInclVat(#[LiveArg] bool $checked): void
    {
        $this->inclVat = !$checked;

        if ($this->inclVat) {
            $this->setPricesInclVat();
        }
    }

    #[PreReRender(-1)]
    public function setVatPrices(): void
    {
        if ($this->inclVat) {
            $this->setPricesInclVat();
        }
    }

  
   
    private function setPricesInclVat(): void
    {
        foreach ($this->pricings as $pricing) {
            $pricing = $pricing * (1 + 0.21));
        }
    }
}

The function setVatPrices() is triggered but does not update the prices. Maybe because $this->prices is not set before render?

1 Answer 1

0

The #[PreReRender] isn't ideal in this case - it doesn't reinitialze or persist state between requests, I would argue for a mount function, which initializes properties on render better.

Also make the inclVat writeable, so you end up with something like this:

#[LiveProp(writable: true)]
public bool $inclVat = false;

public function mount(): void
{
    $this->updatePrices();
}

#[LiveAction]
public function toggleInclVat(#[LiveArg] bool $checked): void
{
    $this->inclVat = $checked;
    $this->updatePrices();
}

private function updatePrices(): void
{
    if ($this->inclVat) {
        $this->setPricesInclVat();
    } else {
        $this->setPricesExclVat();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.