useEffect(() => {
document.title = View Orders | Bothub;
fetch(`${backendAppUrl}/orders/all`, {
...getRequestParams("POST", {
uid: localStorage.uid,
idToken: localStorage.idToken,
user: 0,
pagination: 1,
}),
})
.then((res) => res.json())
.then(
(res) => {
console.log(res);
if (res.detail === "db-error" || res.detail === "forbidden") {
setError(true);
setLoading(false);
} else {
const val = res.data;
setOrders(val);
setLoading(false);
}
},
(err) => {
console.log(err);
setError(true);
setLoading(false);
}
);
// eslint-disable-next-line
}, []);
Why does it show like this and throw an error? Unhandled Rejection (TypeError): Cannot read properties of null (reading 'detail')
If this is showing null in the console:
console.log(res);
Then the JSON response was empty (though somehow still valid I guess) and there's no object to use. So the code needs to be able to handle a null value in res. For example:
if (res?.detail === "db-error" || res?.detail === "forbidden") {
setError(true);
setLoading(false);
} else {
const val = res?.data;
setOrders(val);
setLoading(false);
}
This uses nullish-safe optional chaining to examine the properties of res or just return null. So when res is null then the if condition will be false and the else block will execute.
Alternatively, if you want the system to handle null differently, you'd perform that check in your logic. For example:
if (!res) {
// respond to null in some way here
} else if (res.detail === "db-error" || res.detail === "forbidden") {
setError(true);
setLoading(false);
} else {
const val = res.data;
setOrders(val);
setLoading(false);
}
Any way you structure it, the point is that res is null and your code assumes that it isn't, which produces the error.