T
TanStack•11mo ago
sunny-green

Using setFieldMeta with a dynamic field identifier

For context I am returning some errors from the sever, these errors have the same field name as the fields in the original form, I can use something like formApi.setFieldMeta("email", where the field is statically defined but of the life of me i can figure out how it can accept a variable key that is a string of the name of the field I want to add the custom error to.
Object.entries(e.fieldErrors).forEach(([key, value]) => {
formApi.setFieldMeta(key, (meta) => ({
...meta,
errorMap: { onChange: value },
}));
});
Object.entries(e.fieldErrors).forEach(([key, value]) => {
formApi.setFieldMeta(key, (meta) => ({
...meta,
errorMap: { onChange: value },
}));
});
throws the following typescript error
ts: Argument of type 'string' is not assignable to parameter of type 'PrefixObjectAccessor<RegisterQuery, []>'.
ts: Argument of type 'string' is not assignable to parameter of type 'PrefixObjectAccessor<RegisterQuery, []>'.
is there a way to let formApi.setFieldMeta accept a dynamic field name or do i need to cast the key to a different object? Thank you for your help 🙂
1 Reply
judicial-coral
judicial-coral•10mo ago
Where are you calling your server? If it's something like onSubmitAsync you can let form do the work for you. Instead of calling formApi.setFieldMeta you can simply
return {
fields: {
[yourFieldName]: yourError
},
}
return {
fields: {
[yourFieldName]: yourError
},
}
and form will spread the errors on each field

Did you find this page helpful?