Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda