nuxt / ui

A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
https://ui.nuxt.com
MIT License
3.4k stars 374 forks source link

Form with zod validation dynamically change initial values #1716

Closed guirak closed 2 weeks ago

guirak commented 3 weeks ago

Description

Hello,

I'm using UForm for a componant that can load dynamically the initial value.

I have done the following code :


// Donnée locale en cours de modification
const localData = reactive<Schema>({})
provide('state', localData)

 const validationSchema =  { z.object({
      code: z.string(),
      nom: z.string().min(1)
    })
  }

/**
 * Charge les données systèmes si présentes ou des données par défaut
 */
const loadInitialData = () => {
  if (systemData.value) {
    // On fait une deep copy
    Object.assign(localData, JSON.parse(JSON.stringify(systemData.value)))
  } else {
    // On assigne les valeurs par défaut
    Object.assign(localData, (formProvider.value as IDataFormProvider<K, T>).getNewData())
  }
}

Then I pass the localData to the form :


<UForm 
      :state="localData"
      :schema="validationSchema"
      @submit="saveData">

All seems working well except the errors that are not triggered when the field is empty and I focus out. I think the Object.assign function break the reactivity.

A solution would be to have a ref for the state but the component UForm doesn't watch the change on the state props.

What is the good way to design this use case ?

Thank you

romhml commented 3 weeks ago

I'm not able to reproduce your exact use case here, would you mind sharing a reproduction?Object.assign should work in your case, here's a working example: https://stackblitz.com/edit/nuxt-ui-q9yptv?file=app.vue

Also, you can pass a ref to the UForm component if you want, it'll work just like a reactive object.

guirak commented 2 weeks ago

Hello, I have found why.

I was missing the name attribute in the UFormGroup.

Thank you. :)