React Components not Loading because of uncaught error in bootstrap

Viewed 21

Im trying to initialize my project onto my new computer with the same code, yet im getting an uncaught error in bootstrap for which my react components wont load

Terminal Error

bootstrap:27 Uncaught TypeError: Cannot read properties of undefined (reading 'split')
    at Object.<anonymous> (browser.umd.js:220:1)
    at Object.<anonymous> (browser.umd.js:220:1)
    at r (browser.umd.js:1:1)
    at Object.<anonymous> (browser.umd.js:1012:1)
    at r (browser.umd.js:1:1)
    at Object.<anonymous> (browser.umd.js:1009:1)
    at r (browser.umd.js:1:1)
    at Object.<anonymous> (browser.umd.js:308:1)
    at Object.<anonymous> (browser.umd.js:425:1)
    at r (browser.umd.js:1:1)
    at Object.<anonymous> (browser.umd.js:756:1)
    at r (browser.umd.js:1:1)
    at Object.<anonymous> (browser.umd.js:973:1)
    at Object.<anonymous> (browser.umd.js:977:1)
    at r (browser.umd.js:1:1)
    at Object.<anonymous> (browser.umd.js:973:1)

Package.json and Error in Chrome Console[![][1]][1]][1]

1 Answers

We usually get this TypeError message when we run the split method on undefined.

This could happen if we run a for loop and we set its exit condition (for example: i < str.length) to a length longer than what we intended.

See the example below from freeCodeCamp:

function findLongestWord(str) { 
  for(let i = 0; i < str.length; i++) {
    const array = str.split(" ");
    console.log(array[i]);
    // array[0]: "The"
    // array[1]: "quick"
    // array[2]: "brown"
    // ...
    // array[9]: "dog"
    // array[10]: undefined
    // array[11]: undefined
  }
}

findLongestWord("The quick brown fox jumped over the lazy dog");

In this example, str.length is 44. Therefore, the for loop is incorrectly set to console.log(array[i]) 44 times when in reality array.length is equal to 9 not 44. As a result, array[10] is undefined. And with this in mind, if we try to apply the split() method on undefined, then we get the TypeError: Cannot read property 'split' of undefined.

See the example below:

function findLongestWord(str) { 
  for(let i = 0; i < str.length; i++) {
    const array = str.split(" ");
    array[i].split("");
  }
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Now, see how it could be fixed by setting the for loop exit condition to i < array.length instead of i < str.length:

function findLongestWordLength(str) {
  const array = str.split(" ");
  let maxLength = 0;
  
  for (let i = 0; i < array.length; i++) {
    if (array[i].length > maxLength) {
      maxLength = array[i].length;
    }
  }
    
  return maxLength;
}

I hope this helps you debug your program. However, feel free to post how you're using the split method in your code and we all can help you debug it.

Reference: https://www.freecodecamp.org/news/cannot-read-property-split-of-undefined-error/

Related