React Native Cannot Read Property of Undefined
Got an error like this in your React component?
Cannot read belongings `map` of undefined
In this post nosotros'll talk almost how to fix this one specifically, and along the way you'll learn how to approach fixing errors in full 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 ways you're trying to use .map
on an array, but that assortment isn't divers yet.
That'due south often because the assortment is a slice of undefined state or an undefined prop.
Make sure to initialize the state properly. That means if it will somewhen exist an array, apply useState([])
instead of something like useState()
or useState(null)
.
Permit's look at how nosotros tin can interpret an error message and track down where information technology happened and why.
How to Find the Error
Showtime gild of concern is to figure out where the error is.
If you'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((item) => (
| ^
10 | < div key = {item . id} >
11 | {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 calorie-free gray text above the lawmaking block.
btw, when you run 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 panel instead, you'll need to read the stack trace to figure out where the mistake was.
These e'er expect long and intimidating, only the trick is that normally you tin can ignore well-nigh of it!
The lines are in order of execution, with the most recent first.
Here'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.development.js:16114) at performUnitOfWork (react-dom.evolution.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.render (react-dom.evolution.js:17672) at evaluate (alphabetize.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.eastward. < computed > [as side by side] (runtime.js:97) at t (asyncToGenerator.js:three) at i (asyncToGenerator.js:25)
I wasn't kidding when I said yous could ignore most of information technology! The starting time 2 lines are all we care nearly hither.
The first line is the error message, and every line after that spells out the unwound stack of function calls that led to it.
Permit'southward decode a couple of these lines:
Hither we accept:
-
App
is the name of our component function -
App.js
is the file where it appears -
nine
is the line of that file where the mistake occurred
Permit's look at some other ane:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the office where this happened -
react-dom.development.js
is the file -
15008
is the line number (information technology'due south a large file!)
Ignore Files That Aren't Yours
I already mentioned this just I wanted to state it explictly: when you're looking at a stack trace, you can almost always ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.
Commonly, that ways you'll pay attention to simply the get-go few lines.
Browse down the list until it starts to veer into file names you don't recognize.
There are some cases where you do care about the full stack, but they're few and far between, in my experience. Things like… if y'all doubtable a issues in the library you're using, or if y'all call up some erroneous input is making its way into library code and bravado up.
The vast majority of the fourth dimension, though, the issues will exist in your own code ;)
Follow the Clues: How to Diagnose the Error
And so the stack trace told u.s.a. where to look: line nine of App.js. Let's open that up.
Here'south the full text of that file:
import "./styles.css" ; consign default office App () { allow items ; render ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div key = { detail .id } > { item .name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And just for reference, hither's that error bulletin again:
TypeError: Cannot read property 'map' of undefined
Let'south break this down!
-
TypeError
is the kind of mistake
There are a handful of congenital-in fault types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is non of a valid type." (this office is, IMO, the least useful part of the mistake bulletin)
-
Cannot read property
ways the lawmaking was trying to read a holding.
This is a expert clue! There are only a few ways to read properties in JavaScript.
The nearly mutual is probably the .
operator.
As in user.name
, to access the name
property of the user
object.
Or items.map
, to admission the map
property of the items
object.
There'due south also brackets (aka square brackets, []
) for accessing items in an array, like items[five]
or items['map']
.
You might wonder why the error isn't more than specific, like "Cannot read part `map` of undefined" – just remember, the JS interpreter has no idea what we meant that type to be. It doesn't know it was supposed to be an array, or that map
is a function. Information technology didn't get that far, considering items
is undefined.
-
'map'
is the property the lawmaking was trying to read
This one is another peachy clue. Combined with the previous bit, y'all can be pretty sure yous should be looking for .map
somewhere on this line.
-
of undefined
is a inkling about the value of the variable
It would be way more than useful if the error could say "Cannot read holding `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
So at present you lot can piece this all together:
- discover the line that the mistake occurred on (line nine, here)
- browse that line looking for
.map
- wait at the variable/expression/whatever immediately before the
.map
and exist very suspicious of information technology.
Once you know which variable to look at, you can read through the function looking for where it comes from, and whether it's initialized.
In our little example, the only other occurrence of items
is line 4:
This defines the variable just it doesn't set it to anything, which means its value is undefined
. At that place'due south the problem. Fix that, and you fix the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a elementary error, and it'southward 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 error like this, though.
Perchance items
is a prop passed in from the parent component – and y'all forgot to pass information technology downward.
Or maybe you lot did pass that prop, simply the value existence passed in is actually undefined or cypher.
If it's a local land variable, mayhap you're initializing the state as undefined – useState()
, written like that with no arguments, will do exactly this!
If it's a prop coming from Redux, peradventure your mapStateToProps
is missing the value, or has a typo.
Whatever the case, though, the process is the same: offset 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 audit the intermediate values and figure out why it's undefined.
You'll get information technology fixed! Good luck :)
Success! Now check your email.
Learning React tin exist a struggle — and so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-pace approach, cheque out my Pure React workshop.
Larn to think in React
- ninety+ screencast lessons
- Total transcripts and closed captions
- All the code from the lessons
- Developer interviews
Start learning Pure React at present
Dave Ceddia'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.
Source: https://daveceddia.com/fix-react-errors/
0 Response to "React Native Cannot Read Property of Undefined"
Post a Comment