I just cant figure out how to handle errors here:
const { error, data } = useFetch('https://example.app/api/contact', {
method: "POST",
headers: { "Content-Type": "application/json" },
body: {
name: form.name.value,
email: form.email.value,
message: form.message.value
}
});
console.log(error.value, error)
On error itself it returns ref with _error that contains object with errors. However I cannot get to those errors anyhow..
ref: https://v3.nuxtjs.org/api/composables/use-fetch useFetch return values {data, pending, error, refresh}, here is an example.
const { data, pending, error, refresh } = await useFetch(
'https://api.nuxtjs.dev/mountains',
{
pick: ['title']
}
)
BTW,useFetch return a Promise, in your example, you can do as follows.
useFetch('https://example.app/api/contact', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: {
name: form.name.value,
email: form.email.value,
message: form.message.value
}
}).then(res => {
const data = res.data.value
const error = res.error.value
if (error) {
// dealing error
console.log(error)
} else {
console.log(data)
}
}, error => {
console.log('exception...')
console.log(error)
})
As @Aborn Jiang stated, useFetch returns a Promise. The resolved error-property is a ref.
You could access the error details in Nuxt3 like this:
const { error, data } = await useFetch('https://example.app/api/contact', {...});
console.log(error.value.data);
// Might be interesting as well:
console.log(error.value.name, error.value.message);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With