T
TanStack7mo ago
sunny-green

Getting all errors from field AND subfield

I have three subfields I would like to have a list of errors from. I noticed that there isn't a convenient way to do that, which either means I have to manually call <form>#getFieldMeta() on all subpaths, or get all errors and reduce them based on my parent field's name. Is there an easier way? Example of my implementation:
function allErrorsOfFieldAndSubfield(
fields: Record<
string,
{
errors: ValidationError[];
}
>,
namespace: string,
) {
return Object.entries(fields).reduce<ValidationError[]>((errors, [name, field]) => {
if (!name.startsWith(namespace)) {
return errors;
}
errors.push(...field.errors);
return errors;
}, []);
}

// usage
const errors = allErrorsOfFieldAndSubfield(form.getAllErrors().fields, 'parentKey');
function allErrorsOfFieldAndSubfield(
fields: Record<
string,
{
errors: ValidationError[];
}
>,
namespace: string,
) {
return Object.entries(fields).reduce<ValidationError[]>((errors, [name, field]) => {
if (!name.startsWith(namespace)) {
return errors;
}
errors.push(...field.errors);
return errors;
}, []);
}

// usage
const errors = allErrorsOfFieldAndSubfield(form.getAllErrors().fields, 'parentKey');
2 Replies
rare-sapphire
rare-sapphire7mo ago
GitHub
Commits · TanStack/form
🤖 Headless, performant, and type-safe form state management for TS/JS, React, Vue, Angular, Solid, and Lit. - Commits · TanStack/form
sunny-green
sunny-greenOP7mo ago
could work, but that'd run on every render. There's no store variant you can think of, right? I tried useStore(myForm.store, state => state.fieldMeta['theFieldName'].errors), but that seems buggy as it throws a fieldMeta['...'] is undefined runtime error on mount*. It works after loading.

Did you find this page helpful?