Can Not Read Property Prototype of Undefined Browserify
Got an mistake like this in your React component?
Cannot read property `map` of undefined
In this mail service we'll talk most how to prepare this ane specifically, and along the style you'll acquire how to arroyo fixing errors in general.
We'll cover how to read a stack trace, how to interpret the text of the error, and ultimately how to set it.
The Quick Fix
This mistake usually means you're trying to use .map
on an assortment, but that array isn't defined nevertheless.
That's often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the state properly. That means if it volition eventually exist an array, use useState([])
instead of something like useState()
or useState(goose egg)
.
Let'due south look at how we can translate an error message and track down where it happened and why.
How to Discover the Error
First order of business organization 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
6 | return (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((particular) => (
| ^
10 | < div key = {item . id} >
11 | {item . name}
12 | < / div >
Look for the file and the line number first.
Hither, that's /src/App.js and line nine, taken from the light grey text in a higher place the code block.
btw, when you run into something similar /src/App.js:9:13
, the mode to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If you're looking at the browser console instead, you'll demand to read the stack trace to figure out where the error was.
These always await long and intimidating, just the trick is that unremarkably you can ignore virtually of information technology!
The lines are in club of execution, with the most contempo showtime.
Hither's the stack trace for this error, with the only important lines highlighted:
TypeError: Cannot read property 'map' of undefined at App (App.js:9) at renderWithHooks (react-dom.development.js:10021) at mountIndeterminateComponent (react-dom.development.js:12143) at beginWork (react-dom.development.js:12942) at HTMLUnknownElement.callCallback (react-dom.development.js:2746) at Object.invokeGuardedCallbackDev (react-dom.evolution.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.development.js:15268) at performSyncWorkOnRoot (react-dom.evolution.js:15008) at scheduleUpdateOnFiber (react-dom.development.js:14770) at updateContainer (react-dom.development.js:17211) at eval (react-dom.development.js:17610) at unbatchedUpdates (react-dom.development.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 exist.evaluateTranspiledModule (manager.js:286) at be.evaluateModule (manager.js:257) at compile.ts:717 at l (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.e. < computed > [as next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25)
I wasn't kidding when I said y'all could ignore most of it! The first ii lines are all we care about here.
The first line is the error 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:
Here we accept:
-
App
is the name of our component function -
App.js
is the file where it appears -
9
is the line of that file where the fault occurred
Allow's look at another i:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the proper name of the office where this happened -
react-dom.evolution.js
is the file -
15008
is the line number (information technology's a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to state information technology explictly: when you're looking at a stack trace, you can almost ever ignore any lines that refer to files that are outside your codebase, like ones from a library.
Usually, that means y'all'll pay attention to but the first few lines.
Scan down the list until it starts to veer into file names you don't recognize.
There are some cases where you do care well-nigh the full stack, simply they're few and far betwixt, in my experience. Things similar… if you doubtable a bug in the library yous're using, or if you remember some erroneous input is making its mode into library lawmaking and blowing up.
The vast bulk of the time, though, the bug will be in your ain lawmaking ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told us where to look: line 9 of App.js. Let's open that up.
Here's the full text of that file:
import "./styles.css" ; export default function App () { let items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( particular => ( < div key = { detail .id } > { item .name } </ div > )) } </ div > ) ; }
Line 9 is this ane:
And just for reference, here'south that error message over again:
TypeError: Cannot read property 'map' of undefined
Permit'southward break this downwardly!
-
TypeError
is the kind of error
There are a handful of built-in error types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is non of a valid blazon." (this part is, IMO, the least useful function of the mistake message)
-
Cannot read belongings
means the code was trying to read a belongings.
This is a skilful clue! There are only a few ways to read backdrop in JavaScript.
The most common is probably the .
operator.
As in user.proper name
, to access the name
property of the user
object.
Or items.map
, to admission the map
property of the items
object.
At that place'due south besides brackets (aka square brackets, []
) for accessing items in an array, similar items[five]
or items['map']
.
You might wonder why the fault isn't more specific, like "Cannot read part `map` of undefined" – simply remember, the JS interpreter has no idea what nosotros meant that type to be. It doesn't know it was supposed to be an array, or that map
is a function. It didn't go that far, because items
is undefined.
-
'map'
is the property the code was trying to read
This ane is another great clue. Combined with the previous chip, you tin be pretty certain you should be looking for .map
somewhere on this line.
-
of undefined
is a clue about the value of the variable
It would be style 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.
So now you can slice this all together:
- find the line that the error occurred on (line ix, hither)
- scan that line looking for
.map
- look at the variable/expression/whatsoever immediately before the
.map
and be very suspicious of it.
Once you know which variable to expect at, you can read through the part looking for where it comes from, and whether it's initialized.
In our niggling example, the only other occurrence of items
is line 4:
This defines the variable only it doesn't set it to anything, which means its value is undefined
. At that place's the trouble. Gear up that, and you lot fix the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a simple mistake, and it's colocated very close to the site of the error. These ones are the easiest to fix!
There are a ton of potential causes for an mistake like this, though.
Maybe items
is a prop passed in from the parent component – and yous forgot to laissez passer it down.
Or maybe you did pass that prop, only the value existence passed in is actually undefined or nada.
If it's a local state variable, maybe y'all're initializing the state as undefined – useState()
, written like that with no arguments, will practice exactly this!
If it's a prop coming from Redux, possibly your mapStateToProps
is missing the value, or has a typo.
Whatever the case, though, the procedure is the same: start where the error is and work backwards, verifying your assumptions at each betoken the variable is used. Throw in some console.log
s or use the debugger to inspect the intermediate values and effigy out why it'southward undefined.
You'll go it fixed! Expert luck :)
Success! At present check your electronic mail.
Learning React can be a struggle — so many libraries and tools!
My communication? Ignore all of them :)
For a step-past-pace approach, check out my Pure React workshop.
Learn to call back in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Programmer interviews
Outset learning Pure React at present
Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'grand a React trainer in London and would thoroughly recommend this to all front end end devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Can Not Read Property Prototype of Undefined Browserify"
Post a Comment