Fix issue where error was always reset when a component was re-registered

This commit is contained in:
Andrew Kingston 2022-01-14 09:58:23 +00:00
parent 5e285f29df
commit fabde1b7bf
1 changed files with 18 additions and 10 deletions

View File

@ -141,8 +141,18 @@
return return
} }
// Create validation function based on field schema
const schemaConstraints = schema?.[field]?.constraints
const validator = createValidatorFromConstraints(
schemaConstraints,
validationRules,
field,
table
)
// If we've already registered this field then keep some existing state // If we've already registered this field then keep some existing state
let initialValue = deepGet(initialValues, field) ?? defaultValue let initialValue = deepGet(initialValues, field) ?? defaultValue
let initialError = null
let fieldId = `id-${generateID()}` let fieldId = `id-${generateID()}`
const existingField = getField(field) const existingField = getField(field)
if (existingField) { if (existingField) {
@ -156,20 +166,17 @@
} else { } else {
initialValue = fieldState.value ?? initialValue initialValue = fieldState.value ?? initialValue
} }
// If this field has already been registered and we previously had an
// error set, then re-run the validator to see if we can unset it
if (fieldState.error) {
initialError = validator(initialValue)
}
} }
// Auto columns are always disabled // Auto columns are always disabled
const isAutoColumn = !!schema?.[field]?.autocolumn const isAutoColumn = !!schema?.[field]?.autocolumn
// Create validation function based on field schema
const schemaConstraints = schema?.[field]?.constraints
const validator = createValidatorFromConstraints(
schemaConstraints,
validationRules,
field,
table
)
// Construct field info // Construct field info
const fieldInfo = writable({ const fieldInfo = writable({
name: field, name: field,
@ -178,7 +185,7 @@
fieldState: { fieldState: {
fieldId, fieldId,
value: initialValue, value: initialValue,
error: null, error: initialError,
disabled: disabled || fieldDisabled || isAutoColumn, disabled: disabled || fieldDisabled || isAutoColumn,
defaultValue, defaultValue,
validator, validator,
@ -254,6 +261,7 @@
// Update field state // Update field state
const error = validator ? validator(value) : null const error = validator ? validator(value) : null
console.log("value changed to", value, "new error is", error)
fieldInfo.update(state => { fieldInfo.update(state => {
state.fieldState.value = value state.fieldState.value = value
state.fieldState.error = error state.fieldState.error = error