Created
April 17, 2021 23:41
-
-
Save shaunlee/7bb475746f77e6d41103c9d057584dfb to your computer and use it in GitHub Desktop.
Form state handling wrapped for Vue projects
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
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