Cannot Read Property of Undefined Geocoder.geocode( { Address: Address}, Function(Results,status){
Got an error like this in your React component?
Cannot read holding `map` of undefined
In this post nosotros'll talk near how to prepare this one specifically, and forth the way you lot'll learn how to approach fixing errors in general.
Nosotros'll embrace how to read a stack trace, how to interpret the text of the mistake, and ultimately how to set up it.
The Quick Fix
This error usually means yous're trying to use .map
on an array, but that array isn't divers yet.
That's often because the array is a piece of undefined country or an undefined prop.
Brand sure to initialize the state properly. That means if information technology will eventually be an array, employ useState([])
instead of something similar useState()
or useState(goose egg)
.
Let'due south wait at how we tin can translate an error message and track down where it happened and why.
How to Find the Error
Starting time gild of business is to figure out where the error is.
If you lot'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 >
> nine | {items . map((item) => (
| ^
10 | < div central = {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 lite gray text above the code block.
btw, when you meet 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 demand to read the stack trace to figure out where the error was.
These always look long and intimidating, simply the trick is that unremarkably you tin can ignore nearly of it!
The lines are in gild 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.evolution.js:12143) at beginWork (react-dom.evolution.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 $ane (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.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:7) at z (eval.js:42) at G.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (director.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 > [every bit next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25)
I wasn't kidding when I said you could ignore almost of information technology! The first 2 lines are all we intendance about here.
The start line is the fault message, and every line after that spells out the unwound stack of office calls that led to it.
Permit's decode a couple of these lines:
Here we have:
-
App
is the name of our component role -
App.js
is the file where it appears -
ix
is the line of that file where the mistake occurred
Let'southward 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'southward a large 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 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 but the first few lines.
Scan down the list until it starts to veer into file names you lot don't recognize.
At that place are some cases where you exercise care well-nigh the full stack, merely they're few and far between, in my experience. Things like… if y'all suspect a bug in the library you're using, or if you recollect some erroneous input is making its manner into library code and bravado up.
The vast majority of the time, though, the bug volition be in your own code ;)
Follow the Clues: How to Diagnose the Fault
So the stack trace told us where to look: line ix of App.js. Let'due south open that up.
Here's the full text of that file:
import "./styles.css" ; consign default function App () { permit items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( particular => ( < div primal = { item .id } > { particular .proper name } </ div > )) } </ div > ) ; }
Line ix is this one:
And only for reference, here's that fault message again:
TypeError: Cannot read holding 'map' of undefined
Let's break this downwardly!
-
TypeError
is the kind of error
In that location are a handful of built-in error types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid type." (this function is, IMO, the least useful role of the mistake message)
-
Cannot read property
ways the code was trying to read a property.
This is a skillful inkling! There are only a few ways to read properties in JavaScript.
The most mutual is probably the .
operator.
Every bit 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'southward likewise brackets (aka square brackets, []
) for accessing items in an assortment, like items[5]
or items['map']
.
You might wonder why the error isn't more specific, like "Cannot read role `map` of undefined" – merely remember, the JS interpreter has no idea what we meant that type to be. It doesn't know it was supposed to exist an array, or that map
is a function. It didn't get that far, because items
is undefined.
-
'map'
is the belongings the code was trying to read
This one is another corking clue. Combined with the previous bit, you can exist pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a inkling about the value of the variable
It would exist style more useful if the mistake could say "Cannot read property `map` of items". Sadly information technology doesn't say that. It tells you the value of that variable instead.
So at present you lot can slice this all together:
- find the line that the error occurred on (line ix, here)
- scan that line looking for
.map
- look at the variable/expression/whatsoever immediately earlier the
.map
and be very suspicious of it.
Once you know which variable to wait at, you can read through the office looking for where it comes from, and whether it'southward initialized.
In our little example, the only other occurrence of items
is line 4:
This defines the variable but information technology doesn't set it to anything, which ways its value is undefined
. There's the problem. Fix that, and you fix the error!
Fixing This in the Existent Earth
Of course this case is tiny and contrived, with a unproblematic mistake, and information technology's colocated very close to the site of the fault. These ones are the easiest to set!
There are a ton of potential causes for an fault similar this, though.
Peradventure items
is a prop passed in from the parent component – and you forgot to pass it downwardly.
Or maybe you lot did laissez passer that prop, but the value being passed in is actually undefined or null.
If it's a local country variable, peradventure you're initializing the country as undefined – useState()
, written similar that with no arguments, will do 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 process is the aforementioned: showtime where the fault is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
s or utilize the debugger to inspect the intermediate values and figure out why it'due south undefined.
Yous'll get it fixed! Expert luck :)
Success! At present check your e-mail.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-footstep approach, check out my Pure React workshop.
Learn to recollect in React
- ninety+ screencast lessons
- Full transcripts and closed captions
- All the lawmaking from the lessons
- Developer interviews
Kickoff learning Pure React now
Dave Ceddia's Pure React is a piece of work of enormous clarity and depth. Hats off. I'yard a React trainer in London and would thoroughly recommend this to all forepart terminate devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Cannot Read Property of Undefined Geocoder.geocode( { Address: Address}, Function(Results,status){"
Post a Comment