fix(Form)!: resolve async validation in yup & issue directly mutate state (#2702)

Co-authored-by: Benjamin Canac <canacb1@gmail.com>
This commit is contained in:
kyyy
2024-11-24 01:30:20 +07:00
committed by GitHub
parent 3bccb6782a
commit c9806da6d8
3 changed files with 4 additions and 5 deletions

View File

@@ -104,6 +104,7 @@ function resolveErrorIds(errs: FormError[]): FormErrorWithId[] {
})) }))
} }
const parsedValue = ref<T | null>(null)
async function getErrors(): Promise<FormErrorWithId[]> { async function getErrors(): Promise<FormErrorWithId[]> {
let errs = props.validate ? (await props.validate(props.state)) ?? [] : [] let errs = props.validate ? (await props.validate(props.state)) ?? [] : []
@@ -112,7 +113,7 @@ async function getErrors(): Promise<FormErrorWithId[]> {
if (errors) { if (errors) {
errs = errs.concat(errors) errs = errs.concat(errors)
} else { } else {
Object.assign(props.state, result) parsedValue.value = result
} }
} }
@@ -169,7 +170,7 @@ async function onSubmitWrapper(payload: Event) {
try { try {
await _validate({ nested: true }) await _validate({ nested: true })
event.data = props.state event.data = props.schema ? parsedValue.value : props.state
await props.onSubmit?.(event) await props.onSubmit?.(event)
} catch (error) { } catch (error) {
if (!(error instanceof FormValidationException)) { if (!(error instanceof FormValidationException)) {

View File

@@ -72,7 +72,7 @@ async function validateYupSchema(
schema: YupObjectSchema<any> schema: YupObjectSchema<any>
): Promise<ValidateReturnSchema<typeof state>> { ): Promise<ValidateReturnSchema<typeof state>> {
try { try {
const result = schema.validateSync(state, { abortEarly: false }) const result = await schema.validate(state, { abortEarly: false })
return { return {
errors: null, errors: null,
result result

View File

@@ -422,7 +422,6 @@ describe('Form', () => {
` `
}) })
const form = wrapper.setupState.form const form = wrapper.setupState.form
const state = wrapper.setupState.state
const inputEl = wrapper.find('#input') const inputEl = wrapper.find('#input')
inputEl.setValue(input.value) inputEl.setValue(input.value)
@@ -430,7 +429,6 @@ describe('Form', () => {
form.value.submit() form.value.submit()
await flushPromises() await flushPromises()
expect(state.value).toEqual(expected.value)
expect(wrapper.setupState.onSubmit).toHaveBeenCalledWith(expect.objectContaining({ expect(wrapper.setupState.onSubmit).toHaveBeenCalledWith(expect.objectContaining({
data: expected data: expected
})) }))