Skip to content

Commit

Permalink
fix: run async validator on initialization too
Browse files Browse the repository at this point in the history
  • Loading branch information
YannicEl committed Jan 2, 2024
1 parent 1fb24f1 commit fb1d20f
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions packages/lib/src/useField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,21 +58,25 @@ export function useField<T>(
const async = computed(() => asyncValidators.value.size > 0);
const pending = ref(false);
const asyncErrors = ref<string[]>([]);
watch(value, async (value) => {
if (asyncValidators.value.size === 0) return;

pending.value = true;

const errors = await Promise.all(
Array.from(asyncValidators.value).map(async (validator) => {
const isValid = await validator.validate(value);
if (!isValid) return validator.name;
})
);

asyncErrors.value = errors.filter(Boolean) as string[];
pending.value = false;
});
watch(
value,
async (value) => {
if (asyncValidators.value.size === 0) return;

pending.value = true;

const errors = await Promise.all(
Array.from(asyncValidators.value).map(async (validator) => {
const isValid = await validator.validate(value);
if (!isValid) return validator.name;
})
);

asyncErrors.value = errors.filter(Boolean) as string[];
pending.value = false;
},
{ immediate: true }
);

// combine async and sync errors
const errors = computed(() => [...syncErrors.value, ...asyncErrors.value]);
Expand Down

0 comments on commit fb1d20f

Please sign in to comment.