Unverified Commit 669cad97 authored by Amith Mihiranga's avatar Amith Mihiranga Committed by GitHub

Fix: with-mongodb-mongoose example improper fetch error handling (#15856)

Correct the error handling for fetch API to check if the status is ok or not

FIxes #15808 
parent f9cb5ac6
......@@ -33,6 +33,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
},
body: JSON.stringify(form),
})
// Throw error with status code in case Fetch API req failed
if (!res.ok) {
throw new Error(res.status)
}
const { data } = await res.json()
mutate(`/api/pets/${id}`, data, false) // Update the local data without a revalidation
......@@ -45,7 +51,7 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
/* The POST method adds a new entry in the mongodb database. */
const postData = async (form) => {
try {
await fetch('/api/pets', {
const res = await fetch('/api/pets', {
method: 'POST',
headers: {
Accept: contentType,
......@@ -53,6 +59,12 @@ const Form = ({ formId, petForm, forNewPet = true }) => {
},
body: JSON.stringify(form),
})
// Throw error with status code in case Fetch API req failed
if (!res.ok) {
throw new Error(res.status)
}
router.push('/')
} catch (error) {
setMessage('Failed to add pet')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment