i have a function that fetchs a json data from a server and it must fetch the data if only the condition is met but it excutes the block even if the condition is false
const getOfferingCourses = async () => {
if (typeof loggerInfo === "object") {
if (typeof loggerInfo.section) {
const formdata = new FormData();
formdata.append("getOfferingCourse", loggerInfo.section);
let dep = await fetch(baseUrl + "enroll.php", {
method: "POST",
headers: {
Accept: "application/json",
},
body: formdata,
});
let depa = await dep.json();
if (typeof depa !== "undefined") {
if (depa.status === "success") {
setOffeing(depa.data.offering);
setOffCourses(depa.data.courses);
}
}
}
}
}
this is the error
Uncaught (in promise) TypeError: Cannot read properties of null (reading 'section')
at getSchedule (s-schedule.js:43:1)
at s-schedule.js:61:1
at commitHookEffectListMount (react-dom.development.js:23150:1)
at commitPassiveMountOnFiber (react-dom.development.js:24926:1)
at commitPassiveMountEffects_complete (react-dom.development.js:24891:1)
at commitPassiveMountEffects_begin (react-dom.development.js:24878:1)
at commitPassiveMountEffects (react-dom.development.js:24866:1)
at flushPassiveEffectsImpl (react-dom.development.js:27039:1)
at flushPassiveEffects (react-dom.development.js:26984:1)
at react-dom.development.js:26769:1
2
Answers
References
Differences between null and undefined
why is type of null and object?
Checkout this example
we have null and undefined variables here, we check the type of each of them and while undefined is indeed undefined, null is considered an object.
This line
if (typeof loggerInfo === "object") {
ifloggerInfo
is null then the condition will be true and it will try to read the next lineif (typeof loggerInfo.section) {
which causes the errorthe error occures when you try to check
if (typeof loggerInfo.section)
but as mentionedloggerInfo
isnull
.you may wonder how this is possible inside
if (typeof loggerInfo === "object")
buttypeof null
is equal to"object"
so you need to add another condition in the firstif
statement:also update the second
if
statement this way:or