Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Vee-Validate initial value from API

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

like image 653
o..o Avatar asked May 14 '26 23:05

o..o


2 Answers

if you use vee-validate: "^4.6.9" and vue: "^3.2.39" maybe can use this solution :

  1. add new atribute :initial-values="formValues" in tag form
  2. then inside setup() add:
const formValues = {
  yourFieldName: 'init value',
};
  1. still in setup() return { formValues }

this work for me :D

like image 159
addin Avatar answered May 17 '26 17:05

addin


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,
      },
    })
  }
})
like image 25
Tri Rizki Rifandani Avatar answered May 17 '26 19:05

Tri Rizki Rifandani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!