React Typeerror: Cannot Read Property 'map' of Undefined
Got an error like this in your React component?
Cannot read property `map` of undefined
In this mail service we'll talk about how to fix this one specifically, and forth the way you'll learn how to approach 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 fix it.
The Quick Fix
This error usually means you're trying to use .map
on an assortment, but that array isn't defined still.
That's oft considering the assortment is a piece of undefined state or an undefined prop.
Make sure to initialize the state properly. That means if information technology volition eventually be an array, apply useState([])
instead of something like useState()
or useState(null)
.
Let'south wait at how we can interpret an mistake bulletin and runway downwardly where it happened and why.
How to Find the Mistake
First order of business is to figure out where the mistake is.
If y'all're using Create React App, information technology probably threw upwards a screen like this:
TypeError
Cannot read property 'map' of undefined
App
6 | return (
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div central = {item . id} >
xi | {item . name}
12 | < / div >
Look for the file and the line number kickoff.
Here, that's /src/App.js and line ix, taken from the light greyness text above the code block.
btw, when you see something like /src/App.js:nine:thirteen
, the way to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If y'all're looking at the browser console instead, y'all'll need to read the stack trace to effigy out where the mistake was.
These always await long and intimidating, merely the play tricks is that usually you can ignore most of it!
The lines are in order of execution, with the most recent kickoff.
Here's the stack trace for this error, with the only of import 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.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.development.js:14770) at updateContainer (react-dom.development.js:17211) at eval (react-dom.evolution.js:17610) at unbatchedUpdates (react-dom.evolution.js:15104) at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609) at Object.render (react-dom.development.js:17672) at evaluate (alphabetize.js:vii) at z (eval.js:42) at M.evaluate (transpiled-module.js:692) at exist.evaluateTranspiledModule (manager.js:286) at exist.evaluateModule (manager.js:257) at compile.ts:717 at fifty (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.east. < computed > [as next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25)
I wasn't kidding when I said yous could ignore most of information technology! The first 2 lines are all we care about here.
The commencement line is the fault bulletin, and every line afterward that spells out the unwound stack of office calls that led to it.
Allow's decode a couple of these lines:
Here we 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's wait at some other one:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the function where this happened -
react-dom.evolution.js
is the file -
15008
is the line number (it's a large file!)
Ignore Files That Aren't Yours
I already mentioned this simply I wanted to country it explictly: when you lot're looking at a stack trace, you tin almost always ignore any lines that refer to files that are exterior your codebase, like ones from a library.
Unremarkably, that means you'll pay attention to only the start few lines.
Scan down the listing until it starts to veer into file names you don't recognize.
In that location are some cases where you practise care about the total stack, but they're few and far between, in my experience. Things like… if you suspect a bug in the library you're using, or if you think some erroneous input is making its way into library code and bravado up.
The vast majority of the time, though, the problems will exist in your own lawmaking ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told u.s.a. where to expect: line 9 of App.js. Let's open up that up.
Here's the full text of that file:
import "./styles.css" ; consign default role App () { let items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( particular => ( < div key = { item .id } > { item .name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And only for reference, here'southward that error message again:
TypeError: Cannot read property 'map' of undefined
Allow'southward intermission this downwards!
-
TypeError
is the kind of error
In that location are a scattering of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid type." (this function is, IMO, the least useful role of the error bulletin)
-
Cannot read belongings
means the lawmaking was trying to read a holding.
This is a good clue! There are just a few means to read properties in JavaScript.
The most common is probably the .
operator.
As in user.proper name
, to access the name
holding of the user
object.
Or items.map
, to access the map
belongings of the items
object.
In that location'due south 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 than specific, like "Cannot read function `map` of undefined" – just think, the JS interpreter has no thought what nosotros meant that type to be. Information technology doesn't know it was supposed to be an array, or that map
is a function. It didn't become that far, because items
is undefined.
-
'map'
is the property the lawmaking was trying to read
This one is another nifty 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 nigh the value of the variable
It would be way more useful if the mistake could say "Cannot read holding `map` of items". Sadly it doesn't say that. It tells you lot the value of that variable instead.
And so now you can piece this all together:
- find the line that the error occurred on (line ix, here)
- scan that line looking for
.map
- await at the variable/expression/any immediately before the
.map
and be very suspicious of it.
Once y'all know which variable to look at, you can read through the role looking for where it comes from, and whether it's initialized.
In our little example, the simply other occurrence of items
is line 4:
This defines the variable only it doesn't gear up information technology to anything, which ways its value is undefined
. In that location'southward the trouble. Fix that, and you fix the fault!
Fixing This in the Existent 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 prepare!
At that place are a ton of potential causes for an error like this, though.
Peradventure items
is a prop passed in from the parent component – and yous forgot to pass information technology down.
Or possibly y'all did laissez passer that prop, only the value being passed in is actually undefined or nix.
If it's a local state variable, possibly you'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, peradventure your mapStateToProps
is missing the value, or has a typo.
Whatever the example, though, the process is the aforementioned: first where the mistake is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.log
south or employ the debugger to inspect the intermediate values and figure out why information technology's undefined.
You'll get information technology stock-still! Good luck :)
Success! Now check your email.
Learning React can exist a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step arroyo, check out my Pure React workshop.
Learn to think in React
- ninety+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Programmer interviews
Start learning Pure React at present
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 devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/