skip to Main Content

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


  1. 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") { if loggerInfo is null then the condition will be true and it will try to read the next line if (typeof loggerInfo.section) { which causes the error

    let depa = null;
    let depa2 = undefined;
    
    let nullVar = typeof depa;
    let unVar = typeof depa2;
    
    console.log(nullVar)
    console.log(unVar)
    Login or Signup to reply.
  2. the error occures when you try to check if (typeof loggerInfo.section) but as mentioned loggerInfo is null.
    you may wonder how this is possible inside if (typeof loggerInfo === "object") but typeof null is equal to "object" so you need to add another condition in the first if statement:

    if(typeof loggerInfo === "object" && loggerInfo !== null)
    

    also update the second if statement this way:

    if (typeof loggerInfo.section !== "undefined")
    

    or

    if (loggerInfo.section) 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search