Skip to content

Instantly share code, notes, and snippets.

@shaunlee
Created April 17, 2021 23:41
Show Gist options
  • Save shaunlee/7bb475746f77e6d41103c9d057584dfb to your computer and use it in GitHub Desktop.
Save shaunlee/7bb475746f77e6d41103c9d057584dfb to your computer and use it in GitHub Desktop.
Form state handling wrapped for Vue projects
import { reactive } from '@vue/reactivity'
export function createForm({
form = {},
validate,
submit,
keep = false,
}) {
const state = reactive({
form,
errors: [],
isSending: false,
async submit() {
if (state.isSending) {
return
}
state.errors = []
if (validate) {
const errors = await validate(state.form)
if (errors) {
state.errors = typeof errors === 'string' ? [errors] : errors
return
}
}
state.isSending = true
await submit(state.form).then(() => {
if (!keep) state.form = form
}).finally(() => state.isSending = false)
},
})
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment