Livewire listen for every coming response from the component class

Viewed 493

I'm building a component and I'm using Select2 in my dropdown. here is my view:

<div x-data="{ }" x-init="() => {
    $('.select2').select2();
    $('.select2').change(e => {
        $wire.set('name', e.target.value);

        Livewire.hook('message.processed', (m, component) => {
            $('.select2').select2();
        })

    })
}" class="row mt-5">
<form wire:submit.prevent="send">
    <div class="col-12">
        <p><strong>{{ $name }}</strong></p>
        <br />
        <select wire:model="name" class="form-control select2">
            <option value="">-----select-----</option>
            @foreach($names as $name)
                <option value="{{ $name }}">{{ $name }}</option>
            @endforeach
        </select>
        @error('name') <span class="error">{{ $message }}</span> @enderror
    </div>
    <div class="mt-4 col-12">
        <button type="submit" class="btn btn-success">
            Submit
        </button>
    </div>
</form>

in my alpine code I use "message.processed" hook to reapply Select2 functionality otherwise the component re-render will mess it up. now there is a case if submit the form first thing when page loads and component class responses with validation error in this case this hook never happens and I lose Select2 functionality. what can I do in my javascript side to listen to every response from component class to reapply my select2 coz I didn't find in docs.

0 Answers
Related