nuxt / ui

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

form.value.setErrors is undefined #1927

Open hckhanh opened 4 months ago

hckhanh commented 4 months 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 4 months 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 4 months ago

The onSubmit function is called after the component is mounted

romhml commented 4 months 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

gregorvoinov commented 2 months ago

hi, I run in the same problem. do your response have a path? My solution was to set it manually

const swwError = ref(false); //somethingWentWrongError
const form = ref();
const onSubmit = async (event) => {
  try {
    const data = await authStore.create(event.data);
    router.push("/");
  } catch (error) {
    //email exists already
    if (error.response.status === 422) {
      form.value.setErrors([
        {
          message: error.response.data.message,
          path: "email",
        },
      ]);
    } else {
    // For all other errors, a standard error message is displayed at the top of the form
      swwError.value = true;
    }
  }
github-actions[bot] commented 3 weeks ago

This issue is stale because it has been open for 30 days with no activity.