'Handling errors on nuxt3 usefetch
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..
Solution 1:[1]
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)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
