9 Uncaught Typeerror: Cannot Read Property 'getmap' of Undefined
Got an mistake similar this in your React component?
Cannot read property `map` of undefined
In this post we'll talk near how to gear up this one specifically, and along the way you'll learn how to approach fixing errors in general.
We'll cover how to read a stack trace, how to translate the text of the mistake, and ultimately how to fix information technology.
The Quick Set
This mistake usually means you're trying to use .map
on an array, but that array isn't defined notwithstanding.
That's often because the assortment is a piece of undefined state or an undefined prop.
Brand certain to initialize the land properly. That means if it will somewhen be an array, use useState([])
instead of something similar useState()
or useState(zippo)
.
Permit's await at how we can translate an error message and track downwardly where it happened and why.
How to Notice the Error
Beginning gild of business is to figure out where the error is.
If you're using Create React App, information technology probably threw upwardly a screen like this:
TypeError
Cannot read holding 'map' of undefined
App
vi | return (
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> 9 | {items . map((detail) => (
| ^
10 | < div key = {item . id} >
eleven | {particular . name}
12 | < / div >
Await for the file and the line number outset.
Hither, that'south /src/App.js and line nine, taken from the low-cal grayness text in a higher place the code block.
btw, when you lot run into something like /src/App.js:ix:13
, 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 effigy out where the fault was.
These e'er look long and intimidating, but the flim-flam is that commonly you tin ignore nearly of it!
The lines are in order of execution, with the well-nigh recent starting time.
Here's the stack trace for this fault, with the merely important lines highlighted:
TypeError: Cannot read property 'map' of undefined at App (App.js:nine) at renderWithHooks (react-dom.development.js:10021) at mountIndeterminateComponent (react-dom.development.js:12143) at beginWork (react-dom.evolution.js:12942) at HTMLUnknownElement.callCallback (react-dom.evolution.js:2746) at Object.invokeGuardedCallbackDev (react-dom.development.js:2770) at invokeGuardedCallback (react-dom.evolution.js:2804) at beginWork $1 (react-dom.development.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.development.js:14770) at updateContainer (react-dom.development.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 (alphabetize.js:7) at z (eval.js:42) at Thousand.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (manager.js:286) at be.evaluateModule (manager.js:257) at compile.ts:717 at 50 (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 you lot could ignore virtually of it! The first two lines are all we care nigh hither.
The first line is the fault message, and every line afterwards that spells out the unwound stack of office calls that led to it.
Let'southward decode a couple of these lines:
Hither nosotros have:
-
App
is the name of our component function -
App.js
is the file where information technology appears -
9
is the line of that file where the error occurred
Let'south await at another i:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the office where this happened -
react-dom.evolution.js
is the file -
15008
is the line number (information technology'due south a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to country it explictly: when you're looking at a stack trace, you tin can about e'er ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.
Usually, that means y'all'll pay attention to only the beginning few lines.
Scan down the list until information technology starts to veer into file names you lot don't recognize.
There are some cases where you lot do care near the total stack, but they're few and far betwixt, in my experience. Things similar… if you suspect a problems in the library yous're using, or if you think some erroneous input is making its way into library code and blowing up.
The vast majority of the time, though, the bug will exist in your own code ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told us where to wait: line 9 of App.js. Let's open that upwards.
Hither's the total text of that file:
import "./styles.css" ; export default function App () { let items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div key = { item .id } > { item .name } </ div > )) } </ div > ) ; }
Line ix is this i:
And simply for reference, here's that fault message again:
TypeError: Cannot read holding 'map' of undefined
Let's intermission this down!
-
TypeError
is the kind of error
At that place are a handful of congenital-in error types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful role of the error message)
-
Cannot read property
means the code was trying to read a property.
This is a good inkling! At that place are only a few means to read backdrop in JavaScript.
The virtually common is probably the .
operator.
Every bit in user.proper noun
, to access the proper name
property of the user
object.
Or items.map
, to access the map
property of the items
object.
At that place's besides brackets (aka foursquare brackets, []
) for accessing items in an array, like items[5]
or items['map']
.
Y'all might wonder why the error isn't more specific, like "Cannot read function `map` of undefined" – but remember, the JS interpreter has no thought what we meant that blazon to exist. It doesn't know it was supposed to be an array, or that map
is a role. It didn't get that far, considering items
is undefined.
-
'map'
is the holding the code was trying to read
This one is some other great clue. Combined with the previous bit, y'all can exist pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue almost the value of the variable
It would be way more useful if the mistake could say "Cannot read property `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
And then now yous can piece this all together:
- observe the line that the error occurred on (line 9, here)
- scan that line looking for
.map
- look at the variable/expression/whatever immediately before the
.map
and be very suspicious of it.
Once you know which variable to wait at, you can read through the function looking for where it comes from, and whether information technology'south initialized.
In our footling instance, the only other occurrence of items
is line 4:
This defines the variable just it doesn't prepare it to annihilation, which means its value is undefined
. There's the problem. Fix that, and you fix the error!
Fixing This in the Real World
Of course this case is tiny and contrived, with a unproblematic fault, and it's colocated very shut to the site of the error. These ones are the easiest to fix!
At that place are a ton of potential causes for an mistake like this, though.
Maybe items
is a prop passed in from the parent component – and you forgot to pass it down.
Or maybe you did pass that prop, merely the value existence passed in is actually undefined or null.
If it's a local country variable, maybe you're initializing the country as undefined – useState()
, written like that with no arguments, will practise exactly this!
If it'due south a prop coming from Redux, perhaps your mapStateToProps
is missing the value, or has a typo.
Whatever the case, though, the procedure is the same: first where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
s or use the debugger to inspect the intermediate values and figure out why it's undefined.
You lot'll get information technology fixed! Expert luck :)
Success! At present check your email.
Learning React can exist a struggle — then many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step arroyo, check out my Pure React workshop.
Acquire to think in React
- 90+ screencast lessons
- Full transcripts and airtight captions
- All the code from the lessons
- Developer interviews
Start learning Pure React now
Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front end terminate devs wanting to upskill or consolidate.
9 Uncaught Typeerror: Cannot Read Property 'getmap' of Undefined
Source: https://daveceddia.com/fix-react-errors/