nuxt / ui

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

form.value.setErrors is undefined #1927

Open hckhanh opened 2 days ago

hckhanh commented 2 days ago

Environment

Version

3.12.2

Reproduction

I try to follow this example on docs:

<script setup lang="ts">
import type { FormError, FormSubmitEvent } from '#ui/types'

const state = reactive({
  email: undefined,
  password: undefined
})

const form = ref()

async function onSubmit (event: FormSubmitEvent<any>) {
  form.value.clear()
  try {
    const response = await $fetch('...')
    // ...
  } catch (err) {
    if (err.statusCode === 422) {
      form.value.setErrors(err.data.errors.map((err) => ({
        // Map validation errors to { path: string, message: string }
        message: err.message,
        path: err.path,
      })))
    }
  }
}
</script>

<template>
  <UForm ref="form" :state="state" @submit="onSubmit">
    <UFormGroup label="Email" name="email">
      <UInput v-model="state.email" />
    </UFormGroup>

    <UFormGroup label="Password" name="password">
      <UInput v-model="state.password" type="password" />
    </UFormGroup>

    <UButton type="submit">
      Submit
    </UButton>
  </UForm>
</template>

Description

Is there anything is out of dated compare to the latest version of nuxt?

Additional context

Screenshot 2024-06-29 at 11 51 54

Logs

No response

romhml commented 2 days ago

Hello! It looks like you're trying to use the function before the component is mounted:

form.value?.setErrors(/* ... */); // This will be undefined since the component is not mounted

onMounted(() => {
  form.value.setErrors(/* ... */); // This will be defined
});

See: https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs

hckhanh commented 2 days ago

The onSubmit function is called after the component is mounted

romhml commented 2 days ago

Can you send me a reproduction using Stackblitz so I can have a look? I can't reproduce the issue from the documentation's example