The response.json()
from a backend is an data object which can be if request is OK:
{
"items": [
{
"id": "p2",
"name": "My Second Book",
"price": 8.98,
"quantity": 2,
"totalPrice": 17.96
},
{
"id": "p1",
"name": "My First Book",
"price": 6.99,
"quantity": 3,
"totalPrice": 20.97
}
],
"totalQuantity": 5
}
Or if there any error, it responses with this object:
{
"code": 404,
"description": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.",
"message": "Not Found"
}
The function for fetching request exports dispatch result.
export function fetchCartData() {
return async (dispatch) => {
const fetchData = async () => {
const response = await fetch("http://127.0.0.1:5000/api/cart");
const result = await response.json();
if (!response.ok) {
console.log(result);
throw new Error(result);
} else {
console.log(result);
return result;
}
};
try {
const cartData = await fetchData();
dispatch(cartActions.replaceCart(cartData));
} catch (error) {
// console.log(error);
dispatch(
uiActions.showNotification({
status: "error",
title: "Error!",
message: "Fetching cart data failed!",
})
);
}
};
}
The goal of fetchData
function nested is sending GET
request to API, store OK or not OK response in constant result
and pass it to try-catch
for handle response or error.
if response is OK
in fetchData
function, try
dispatch it, but when response is not OK
the object result brings information such message: Not Found
which I want to pass to catch(error)
for replacing in message into ‘dispatch(uiActions.showNotification({message:` key.
I tried returning result
when response is not OK but it still does not pass object to catch
, for example:
if (!response.ok) {
console.log(result);
return result;
}