Error Typeerror: Cannot Read Property 'push' of Undefined
Got an error like this in your React component?
Cannot read property `map` of undefined
In this mail nosotros'll talk about how to ready this one specifically, and along the way you'll learn how to approach fixing errors in general.
Nosotros'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 unremarkably means yous're trying to use .map
on an array, but that assortment isn't defined yet.
That'due south often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the country properly. That means if it will eventually exist an array, utilize useState([])
instead of something similar useState()
or useState(cypher)
.
Let's look at how we can translate an error bulletin and track down where it happened and why.
How to Discover the Error
Beginning order of business is to effigy out where the error is.
If you're using Create React App, it probably threw upwards 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((item) => (
| ^
ten | < div key = {particular . id} >
xi | {item . name}
12 | < / div >
Look for the file and the line number first.
Here, that's /src/App.js and line 9, taken from the light grayness text above the code block.
btw, when you see 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 panel instead, you'll need to read the stack trace to effigy out where the error was.
These always expect long and intimidating, but the fob is that usually you can ignore about of it!
The lines are in order of execution, with the most recent first.
Here'southward the stack trace for this mistake, with the just important lines highlighted:
TypeError: Cannot read belongings '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.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.development.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.development.js:15104) at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609) at Object.return (react-dom.development.js:17672) at evaluate (index.js:seven) 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.due east. < computed > [as adjacent] (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 it! The get-go 2 lines are all we care about hither.
The first line is the mistake bulletin, and every line after that spells out the unwound stack of function calls that led to it.
Permit's decode a couple of these lines:
Hither we have:
-
App
is the proper noun of our component function -
App.js
is the file where it appears -
9
is the line of that file where the error occurred
Permit's look at another one:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the function where this happened -
react-dom.development.js
is the file -
15008
is the line number (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this just I wanted to land it explictly: when you're looking at a stack trace, you can almost always ignore any lines that refer to files that are outside your codebase, like ones from a library.
Unremarkably, that ways you'll pay attention to merely the first few lines.
Scan down the list until information technology starts to veer into file names you don't recognize.
There are some cases where you lot do intendance near the full stack, but they're few and far between, 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 style into library code and bravado up.
The vast majority of the time, though, the bug will exist in your own lawmaking ;)
Follow the Clues: How to Diagnose the Error
And so the stack trace told us where to wait: line 9 of App.js. Let's open that upward.
Hither'due south the full text of that file:
import "./styles.css" ; consign default function App () { let items ; render ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div primal = { item .id } > { particular .name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And but for reference, here's that error message again:
TypeError: Cannot read holding 'map' of undefined
Let's interruption this down!
-
TypeError
is the kind of error
There are a handful of born error types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is not of a valid blazon." (this role is, IMO, the to the lowest degree useful role of the fault message)
-
Cannot read property
means the code was trying to read a property.
This is a good clue! There are simply a few ways to read properties in JavaScript.
The nigh common is probably the .
operator.
As in user.proper noun
, to admission the name
property of the user
object.
Or items.map
, to access the map
holding of the items
object.
There's also brackets (aka square brackets, []
) for accessing items in an array, like items[v]
or items['map']
.
You might wonder why the error isn't more specific, like "Cannot read function `map` of undefined" – but recall, the JS interpreter has no idea what nosotros meant that type to be. Information technology doesn't know it was supposed to be an assortment, or that map
is a function. It didn't get that far, because items
is undefined.
-
'map'
is the property the code was trying to read
This one is another great clue. Combined with the previous bit, you lot can be pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue well-nigh the value of the variable
It would exist way more useful if the fault could say "Cannot read holding `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
Then now y'all can piece this all together:
- find the line that the error occurred on (line nine, here)
- scan that line looking for
.map
- await at the variable/expression/whatsoever immediately earlier the
.map
and be very suspicious of it.
One time y'all know which variable to await at, you can read through the role looking for where it comes from, and whether it's initialized.
In our trivial example, the only other occurrence of items
is line iv:
This defines the variable but information technology doesn't set it to anything, which ways its value is undefined
. There'south the problem. Fix that, and y'all prepare the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a elementary error, and it'due 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.
Peradventure items
is a prop passed in from the parent component – and you forgot to pass information technology down.
Or peradventure y'all did pass that prop, just the value existence passed in is actually undefined or zilch.
If it'due south a local state variable, maybe y'all're initializing the state as undefined – useState()
, written similar 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 case, 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 console.log
southward or use the debugger to inspect the intermediate values and figure out why it's undefined.
You lot'll become information technology fixed! Proficient luck :)
Success! At present cheque your email.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, check out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Start learning Pure React now
Dave Ceddia's Pure React is a piece of work of enormous clarity and depth. Hats off. I'grand a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.
edmondstoneinvuld.blogspot.com
Source: https://daveceddia.com/fix-react-errors/