How to get data only if the data is not filled in front-end using livewire and alpinejs?

Viewed 85

For using less resources I want to fetch data from the server (using livewire) only for the first time and the other times to use the already fetched data in alpinejs.

So if there is a change in my <select>, the fillStates will be triggered:

<select wire:model="selectedCountry" name="selectedCountry" id="selectedCountry" wire:change="fillStates">
    <option value="">Select Country</option>
    @foreach($this->countries as $country)
        <option value="{{ $country->id }}">{{ $country->name }}</option>
    @endforeach
</select>

The fillStates method will return the data:

public function fillStates()
{
    $states = State::where('country_id', $this->selectedCountry)->get();
    if(count($states)) {
        $this->states[$this->selectedCountry] = $states;

        return $this->states[$this->selectedCountry];
    }

    return [];
}

And my question is here. How can I prevent it requesting more than one time when the $this->states[$country] has already value and can be accessed with alpinejs?

For example I select United States in my <select>. For the first time it needs to fetch the data which is its states. I change it to Canada. This time it needs to fetch the data which is its states. But if I select the United States again, it shouldn't request as it has already fetched and is available in alpinejs. How can I achieve it?

1 Answers

I think you have to manually validate using alpinejs.

<div x-data="{
    selectedCountry: null,
    countries: {},
}"
x-init="$watch('selectedCountry', () => {
    if(! (selectedCountry in countries)) {
        @this.call('fillStates');
        countries[selectedCountry] = @this.get('states');
    }
})"
>
<select x-model="selectedCountry" name="selectedCountry" id="selectedCountry" >
    <option value="">Select Country</option>
    @foreach($this->countries as $country)
        <option value="{{ $country->id }}">{{ $country->name }}</option>
    @endforeach
</select>
</div>
Related