42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
import { Controller } from "stimulus"
|
|
|
|
export default class extends Controller {
|
|
connect() {
|
|
this.onClick = this.onClick.bind(this);
|
|
this.element.addEventListener('click', this.onClick);
|
|
}
|
|
|
|
disconnect() {
|
|
this.element.removeEventListener('click', this.onClick);
|
|
}
|
|
|
|
onClick(evt) {
|
|
evt.preventDefault();
|
|
|
|
const config = {
|
|
method: this.data.get('method') || 'GET',
|
|
};
|
|
|
|
if (this.data.has('payload')) {
|
|
config.body = this.data.get('payload');
|
|
}
|
|
|
|
const endpoint = this.data.get('endpoint');
|
|
|
|
fetch(endpoint, config)
|
|
.then(res => {
|
|
if (res.status < 200 && res.status >= 400) {
|
|
throw new Error(`Unexpected server response: ${res.status} - ${res.statusText}`);
|
|
}
|
|
return res;
|
|
})
|
|
.then(() => {
|
|
const redirect = this.data.get('redirect');
|
|
if (redirect) {
|
|
window.location = redirect;
|
|
} else {
|
|
window.location.reload();
|
|
}
|
|
})
|
|
}
|
|
} |