Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda