-
-
Save niladam/aaf62b7b5641f514328cf5a7409aa243 to your computer and use it in GitHub Desktop.
Form plugin for Alpine.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| document.addEventListener('alpine:init', () => { | |
| Alpine.magic('form', el => () => { | |
| return Alpine.reactive({ | |
| processing: false, | |
| recentlySuccessful: false, | |
| errors: {}, | |
| submit() { | |
| return axios.post(el.action, el).then(response => { | |
| this.errors = {}; | |
| this.recentlySuccessful = true; | |
| this.dispatch('success', response.data); | |
| setTimeout(() => this.recentlySuccessful = false, 3000); | |
| return Promise.resolve(response.data); | |
| }).catch(({ response }) => { | |
| this.dispatch('error', response); | |
| this.errors = response.data.errors ?? {}; | |
| return Promise.reject(response); | |
| }).finally(() => this.dispatch('finish')); | |
| }, | |
| dispatch(event, data) { | |
| el.dispatchEvent(new CustomEvent(event, { detail: data, bubbles: true })); | |
| }, | |
| }); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment