Uncaught Typeerror: Cannot Read Property '0' of Undefined at Xmlhttprequest.weatherrequest.onload (
Got an error like this in your React component?
Cannot read property `map` of undefined
In this postal service we'll talk most how to fix 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 translate the text of the mistake, and ultimately how to fix it.
The Quick Fix
This mistake unremarkably means you're trying to employ .map
on an array, merely that array isn't divers nonetheless.
That's often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the country properly. That ways if it will eventually be an assortment, use useState([])
instead of something similar useState()
or useState(null)
.
Let's look at how we can interpret an error bulletin and track down where it happened and why.
How to Find the Error
First order of business 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 holding 'map' of undefined
App
6 | return (
vii | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((particular) => (
| ^
10 | < div primal = {particular . id} >
eleven | {item . proper name}
12 | < / div >
Await for the file and the line number beginning.
Here, that'due south /src/App.js and line ix, taken from the light gray text above the lawmaking block.
btw, when you see something like /src/App.js:9:thirteen
, the style to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If yous're looking at the browser console instead, you lot'll need to read the stack trace to figure out where the mistake was.
These always wait long and intimidating, but the trick is that usually you tin ignore most of information technology!
The lines are in order of execution, with the virtually recent get-go.
Here's the stack trace for this error, with the just important lines highlighted:
TypeError: Cannot read property 'map' of undefined at App (App.js:nine) at renderWithHooks (react-dom.evolution.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.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.evolution.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.development.js:17672) at evaluate (index.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 fifty (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.e. < computed > [as side by side] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25)
I wasn't kidding when I said you could ignore near of it! The get-go 2 lines are all we care virtually here.
The first line is the error message, and every line afterwards that spells out the unwound stack of office calls that led to information technology.
Let'south decode a couple of these lines:
Hither we have:
-
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 error occurred
Let's wait 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 (information technology's a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to state it explictly: when yous're looking at a stack trace, y'all can nearly always ignore whatsoever lines that refer to files that are exterior your codebase, like ones from a library.
Usually, that ways you'll pay attention to but the start few lines.
Browse down the listing until it starts to veer into file names you don't recognize.
There are some cases where you do care about the total stack, but they're few and far between, in my experience. Things like… if y'all suspect a problems in the library y'all're using, or if you call up some erroneous input is making its manner into library code and blowing up.
The vast majority of the fourth dimension, though, the bug will be in your own code ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told united states where to look: line 9 of App.js. Let'due south open that upwards.
Here's the full 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 = { detail .id } > { item .proper name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And only for reference, here'south that error message again:
TypeError: Cannot read holding 'map' of undefined
Let's break this down!
-
TypeError
is the kind of error
At that place are a handful of congenital-in mistake types. MDN says TypeError "represents an fault that occurs when a variable or parameter is non of a valid type." (this part is, IMO, the least useful part of the error message)
-
Cannot read belongings
ways the code was trying to read a property.
This is a good inkling! There are only a few ways to read properties in JavaScript.
The most mutual is probably the .
operator.
As in user.name
, to access the proper noun
property of the user
object.
Or items.map
, to access the map
holding of the items
object.
At that place'southward as well brackets (aka foursquare brackets, []
) for accessing items in an array, like items[five]
or items['map']
.
Y'all might wonder why the error isn't more specific, like "Cannot read function `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 be an array, 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, yous tin can be pretty certain you should exist looking for .map
somewhere on this line.
-
of undefined
is a clue about 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.
So at present you tin can piece this all together:
- find the line that the fault occurred on (line ix, here)
- scan that line looking for
.map
- wait at the variable/expression/whatever immediately earlier the
.map
and be very suspicious of it.
In one case you know which variable to expect at, yous tin read through the function looking for where information technology comes from, and whether it'southward initialized.
In our little example, the just other occurrence of items
is line 4:
This defines the variable but it doesn't gear up information technology to anything, which means its value is undefined
. In that location's the problem. Fix that, and y'all fix the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a simple mistake, and information technology's colocated very close to the site of the mistake. These ones are the easiest to fix!
There are a ton of potential causes for an error similar 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, but the value being passed in is really undefined or cypher.
If it's a local country variable, maybe y'all're initializing the state as undefined – useState()
, written like that with no arguments, volition do exactly this!
If information technology's a prop coming from Redux, maybe your mapStateToProps
is missing the value, or has a typo.
Whatsoever the case, though, the procedure is the same: beginning where the mistake 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's undefined.
Yous'll get it fixed! Good luck :)
Success! Now check your e-mail.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a pace-by-pace approach, check out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Full transcripts and airtight captions
- All the code from the lessons
- Developer interviews
Showtime 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 forepart devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Uncaught Typeerror: Cannot Read Property '0' of Undefined at Xmlhttprequest.weatherrequest.onload ("
Enviar um comentário