I'm trying to use Vee-Validate and I'm struggling with using initial values loaded from API and getting the value whether the form is dirty or not.
<script setup lang="ts">
const model: Ref<Company | any> = ref({})
const { handleSubmit, errors, meta } = useForm({
validationSchema: {
name: yup.string().required("Name is required")
},
initialValues: model
})
const handleCompanyOverviewSave = handleSubmit(async (form: any) => {
console.log(meta.value.dirty) // here it is always true
})
onMounted(async () => {
const api = useApi()
model.value = (await api.get(`/companies/${store.currentCompany.id}`)).data
})
</script>
The thing is, when I use a simple object like { name: "test" } as the initial value, the meta.dirty is really true only when I change the field.
But when I use the model loaded from the API and assign it to the ref object, it is becoming dirty by the assignment itself - I understand that.
But what is the correct way to set initial values to the useForm from API?
Thanks
if you use vee-validate: "^4.6.9" and vue: "^3.2.39" maybe can use this solution :
:initial-values="formValues" in tag formconst formValues = {
yourFieldName: 'init value',
};
this work for me :D
if you are using @tanstack/vue-query, you can do something like this:
const { isLoading, isSuccess, error, data } = useQuery({
enabled,
queryKey,
queryFn: () => todoApi.detail(queryKey.value[2]),
})
const initialValues: UpdateTodoSchema = {
id: 1,
completed: false,
todo: t('common.loading'),
}
const { defineField, handleSubmit, isSubmitting, resetForm } = useForm<UpdateTodoSchema>({
initialValues,
validationSchema: toTypedSchema(updateTodoSchema),
})
watch([data], () => {
if (data.value) {
resetForm({
values: {
id: data.value.id,
completed: data.value.completed,
todo: data.value.todo,
},
})
}
})
be aware that using watchEffect like below doesn't work to me:
watchEffect(() => {
if (data.value) {
resetForm({
values: {
id: data.value.id,
completed: data.value.completed,
todo: data.value.todo,
},
})
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With