Typeerror: Cannot Read Property 'cancompile' of Undefined Babelify
Got an error like this in your React component?
Cannot read property `map` of undefined
In this mail nosotros'll talk about how to fix this one specifically, and forth the way you'll learn how to approach fixing errors in general.
Nosotros'll embrace how to read a stack trace, how to translate the text of the fault, and ultimately how to fix information technology.
The Quick Fix
This error usually ways you're trying to use          .map          on an array, but that array isn't defined yet.
That's often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the land properly. That means if information technology volition          eventually          be an array, utilise          useState([])          instead of something like          useState()          or          useState(null).
Permit's wait at how we tin can interpret an error message and track down where it happened and why.
How to Find the Error
First club of business is to figure out where the error is.
If yous're using Create React App, it probably threw up a screen like this:
TypeError
Cannot read property 'map' of undefined
App
                                                                                                                          half-dozen |                                                      return                                      (                                
                                                                                          vii |                                                                        <                                    div                                      className                  =                                    "App"                                    >                                                  
                                                                                          8 |                                                                        <                                    h1                                    >                                    List                                      of                                    Items                                    <                                    /                                    h1                                    >                                                  
                                                                      >                                                                          nine |                                                        {items                  .                  map((item)                                    =>                                      (                                
                                                                                          |                                                                                          ^                                                                    
                                                                                          x |                                                                        <                                    div                                      key                  =                  {item                  .                  id}                  >                                                  
                                                                                          eleven |                                                        {item                  .                  name}                                
                                                                                          12 |                                                                        <                                    /                                    div                                    >                                                                                        Look for the file and the line number first.
Here, that's /src/App.js and line ix, taken from the light grey text to a higher place the code cake.
btw, when you lot come across something like          /src/App.js:9:thirteen, the way to decode that is          filename:lineNumber:columnNumber.
How to Read the Stack Trace
If you're looking at the browser console instead, you'll need to read the stack trace to figure out where the error was.
These ever look long and intimidating, just the trick is that usually you can ignore most of it!
The lines are in social club of execution, with the nigh contempo beginning.
Hither'south the stack trace for this error, with the only important lines highlighted:
                                          TypeError: Cannot                                read                                  property                                'map'                                  of undefined                                                              at App (App.js:ix)                                            at renderWithHooks (react-dom.development.js:10021)                              at mountIndeterminateComponent (react-dom.evolution.js:12143)                              at beginWork (react-dom.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $1                              (react-dom.evolution.js:16114)                              at performUnitOfWork (react-dom.development.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.evolution.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.evolution.js:14770)                              at updateContainer (react-dom.evolution.js:17211)                              at                            eval                              (react-dom.development.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.return (react-dom.development.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at exist.evaluateModule (director.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.due east.              <              computed              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                              I wasn't kidding when I said you could ignore most of it! The kickoff 2 lines are all we care nearly here.
The first line is the fault message, and every line after that spells out the unwound stack of function calls that led to it.
Let's decode a couple of these lines:
Hither we have:
-             
Appis the proper name of our component part -             
App.jsis the file where it appears -             
9is the line of that file where the error occurred 
Allow's look at another ane:
                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                            -             
performSyncWorkOnRootis the proper name of the function where this happened -             
react-dom.development.jsis the file -             
15008is the line number (it'southward a big file!) 
Ignore Files That Aren't Yours
I already mentioned this but I wanted to state it explictly: when y'all're looking at a stack trace, you lot tin can almost e'er ignore whatsoever lines that refer to files that are outside your codebase, similar ones from a library.
Ordinarily, that means you'll pay attention to merely the first few lines.
Browse downwards the list until it starts to veer into file names you don't recognize.
There are some cases where you lot do care about the full stack, merely they're few and far betwixt, in my experience. Things like… if you doubtable a bug in the library you're using, or if you think some erroneous input is making its way into library code and blowing upwardly.
The vast majority of the time, though, the bug volition be in your own code ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told united states where to await: line nine of App.js. Let's open up that upwardly.
Hither'south the full text of that file:
                          import                                          "./styles.css"              ;              export                                          default                                          function                                          App              ()                                          {                                          allow                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                              Line 9 is this 1:
And just for reference, here'south that error bulletin again:
                          TypeError: Cannot read holding 'map' of undefined                                            Let's suspension this downwards!
-             
TypeErroris the kind of error 
There are a handful of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this role is, IMO, the to the lowest degree useful office of the fault message)
-             
Cannot read propertyways the code was trying to read a holding. 
This is a good clue! At that place are just a few ways to read backdrop in JavaScript.
The most common is probably the          .          operator.
Every bit in          user.name, to access the          name          property of the          user          object.
Or          items.map, to access the          map          belongings of the          items          object.
At that place's also brackets (aka square brackets,          []) for accessing items in an array, similar          items[v]          or          items['map'].
You might wonder why the error isn't more specific, like "Cannot read          function          `map` of undefined" – but retrieve, the JS interpreter has no idea what we meant that type to be. Information technology doesn't know it was supposed to be an array, or that          map          is a part. It didn't get that far, considering          items          is undefined.
-             
'map'is the property the code was trying to read 
This one is another great clue. Combined with the previous flake, you can be pretty sure yous should be looking for          .map          somewhere on this line.
-             
of undefinedis a inkling about the value of the variable 
Information technology would exist way more than useful if the error could say "Cannot read belongings `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
Then now you can piece this all together:
- detect the line that the error occurred on (line ix, hither)
 - browse that line looking for            
.map - look at the variable/expression/whatever immediately before the            
.mapand be very suspicious of information technology. 
Once you know which variable to look at, yous tin can read through the function looking for where it comes from, and whether it's initialized.
In our little instance, the only other occurrence of          items          is line 4:
This          defines          the variable simply it doesn't set information technology to anything, which means its value is          undefined. In that location's the problem. Fix that, and y'all fix the error!
Fixing This in the Real World
Of course this instance is tiny and contrived, with a simple fault, and it'south colocated very close to the site of the fault. These ones are the easiest to fix!
There are a ton of potential causes for an error like this, though.
Perhaps          items          is a prop passed in from the parent component – and you forgot to laissez passer it down.
Or peradventure you did pass that prop, only the value existence passed in is actually undefined or null.
If it's a local country variable, maybe you're initializing the country equally undefined –          useState(), written like that with no arguments, will do exactly this!
If it's a prop coming from Redux, maybe your          mapStateToProps          is missing the value, or has a typo.
Whatever the example, though, the process is the same: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some          panel.logdue south or utilise the debugger to inspect the intermediate values and effigy out why it'southward undefined.
You'll get information technology fixed! Skillful luck :)
Success! At present check your electronic mail.
            Learning React can exist a struggle — so many libraries and tools!
            My advice? Ignore all of them :)
            For a footstep-by-step arroyo, check out my Pure React workshop.          
              
            
Larn to retrieve in React
- 90+ screencast lessons
 - Total transcripts and airtight captions
 - All the code from the lessons
 - Developer interviews
 
Commencement learning Pure React now
Dave Ceddia'due south Pure React is a piece of work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.
Typeerror: Cannot Read Property 'cancompile' of Undefined Babelify
Source: https://daveceddia.com/fix-react-errors/
              
0 Response to "Typeerror: Cannot Read Property 'cancompile' of Undefined Babelify"
Post a Comment