Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!