cheesegrits / filament-google-maps

Google Maps package for Filament PHP
230 stars 65 forks source link

Lng not set in state variable in afterStateUpdated method #62

Open brain82 opened 10 months ago

brain82 commented 10 months ago

See screenshots below.

image

image

khairy-pelcro commented 9 months ago

I have the same issue also @brain82 have you found a solution for it?

brain82 commented 9 months ago

@khairy-pelcro After quite a bit of messing about to identify the cause, I found that it was an issue with Livewire and not the component (see the comment in code block below).

I ended up extending the Geocomplete field and changing the way the state and getFormattedState functions work.

namespace App\Forms\Components;

use Cheesegrits\FilamentGoogleMaps\Fields\Geocomplete;

class CustomGeocomplete extends Geocomplete
{
    public function state(mixed $state): static
    {
        if ($this->getIsLocation() && is_array($state)) {
            // IMPORTANT
            // If all keys in the array are not set, it is important to set the state to null
            // Otherwise, a livewire bug will occur where only the first key in the array will be set
            // when the state is referenced in the afterStateUpdated callback

            $lat = $state['lat'] ?? null;
            $lng = $state['lng'] ?? null;

            if (empty($lat) || empty($lng)) {
                $state = null;
            }
        }

        return parent::state($state);
    }

    public function getFormattedState(): string
    {
        $state = $this->getState();

        if ($this->getIsLocation()) {
            return $state ? $state['formatted_address'] ?? '' : '';
        }

        return $state;
    }
}
khairy-pelcro commented 9 months ago

Thanks really appracited