vue.jsvee-validate

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


Solution

  • 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