import {Controller} from '@hotwired/stimulus'; /* * The following line makes this controller "lazy": it won't be downloaded until needed * See https://github.com/symfony/stimulus-bridge#lazy-controllers */ /* stimulusFetch: 'lazy' */ export default class extends Controller { static targets = ['icon'] connect() { this.defaultIconClass = this.iconTarget.classList.value; } async handleClick(event) { event.preventDefault(); const button = event.currentTarget; const url = button.dataset.url; // Change the icon to a loader this.iconTarget.classList.remove("fa-search"); this.iconTarget.classList.add("fa-spinner"); this.iconTarget.classList.add("fa-spin"); try { const response = await fetch(`${url}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } }); const data = await response.json(); // Handle the response data as needed if(data.error){ this.dispatchAlert(data.error, 'error'); }else if(data.success) { this.dispatchAlert(data.success, 'success'); } } catch (error) { console.error('Error:', error); } finally { // Revert the icon back to the original one this.iconTarget.classList.value = this.defaultIconClass; } } dispatchAlert(message, level) { const event = new CustomEvent('alert:show', { detail: { message: message, level: level } }); window.dispatchEvent(event); } }