Webpack Typeerror: Cannot Read Property '0' of Undefined
Got an error like this in your React component?
Cannot read property `map` of undefined
In this post we'll talk about how to fix this one specifically, and along the way y'all'll acquire how to approach fixing errors in general.
We'll encompass how to read a stack trace, how to interpret the text of the error, and ultimately how to gear up information technology.
The Quick Fix
This error usually means yous're trying to use .map
on an array, but that array isn't defined yet.
That's oft because the array is a piece of undefined state or an undefined prop.
Brand sure to initialize the land properly. That means if it will eventually be an array, use useState([])
instead of something like useState()
or useState(null)
.
Let'south look at how we can interpret an error message and track down where it happened and why.
How to Discover the Error
Start club of business is to figure out where the fault is.
If you're using Create React App, it probably threw up a screen similar this:
TypeError
Cannot read property 'map' of undefined
App
half-dozen | render (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> ix | {items . map((item) => (
| ^
x | < div key = {item . id} >
11 | {item . proper name}
12 | < / div >
Await 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 code block.
btw, when you see something similar /src/App.js:9: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 need to read the stack trace to effigy out where the error was.
These always look long and intimidating, but the trick is that usually you lot tin can ignore most of it!
The lines are in order of execution, with the most contempo first.
Here'southward the stack trace for this error, with the but 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.evolution.js:12942) at HTMLUnknownElement.callCallback (react-dom.evolution.js:2746) at Object.invokeGuardedCallbackDev (react-dom.development.js:2770) at invokeGuardedCallback (react-dom.development.js:2804) at beginWork $one (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.development.js:15008) at scheduleUpdateOnFiber (react-dom.evolution.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:seven) at z (eval.js:42) at Yard.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (managing director.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.due east. < computed > [as next] (runtime.js:97) at t (asyncToGenerator.js:iii) at i (asyncToGenerator.js:25)
I wasn't kidding when I said you could ignore about of it! The first 2 lines are all we care almost here.
The first line is the error message, and every line later on that spells out the unwound stack of function calls that led to it.
Permit's decode a couple of these lines:
Here we take:
-
App
is the name of our component office -
App.js
is the file where it appears -
nine
is the line of that file where the error occurred
Permit's look at another one:
at performSyncWorkOnRoot (react-dom.evolution.js:15008)
-
performSyncWorkOnRoot
is the proper noun of the function where this happened -
react-dom.development.js
is the file -
15008
is the line number (it'due south a big file!)
Ignore Files That Aren't Yours
I already mentioned this only I wanted to state it explictly: when you lot're looking at a stack trace, you can almost always ignore whatever lines that refer to files that are outside your codebase, like ones from a library.
Usually, that means you'll pay attention to only the kickoff few lines.
Scan down the list until it starts to veer into file names y'all don't recognize.
In that location are some cases where you do care about the full stack, merely 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 blowing up.
The vast majority of the time, though, the issues volition be in your own code ;)
Follow the Clues: How to Diagnose the Fault
So the stack trace told united states of america where to look: line 9 of App.js. Let'due south open that upwardly.
Here'due south the total text of that file:
import "./styles.css" ; consign default function App () { let items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div key = { item .id } > { detail .name } </ div > )) } </ div > ) ; }
Line nine is this 1:
And but for reference, here's that error message again:
TypeError: Cannot read holding 'map' of undefined
Permit'southward suspension this downwards!
-
TypeError
is the kind of error
There are a handful of born error types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful part of the error bulletin)
-
Cannot read holding
ways the code was trying to read a property.
This is a adept clue! At that place are only a few ways to read backdrop in JavaScript.
The virtually 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.
In that location's also brackets (aka foursquare brackets, []
) for accessing items in an array, like items[five]
or items['map']
.
You might wonder why the mistake isn't more specific, similar "Cannot read function `map` of undefined" – simply call up, the JS interpreter has no idea what we meant that type to exist. It doesn't know it was supposed to exist an array, or that map
is a function. Information technology didn't get that far, considering items
is undefined.
-
'map'
is the belongings the code was trying to read
This one is another cracking clue. Combined with the previous fleck, you tin can be pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue most the value of the variable
It would exist way more useful if the error could say "Cannot read belongings `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
So now you can slice this all together:
- find the line that the error occurred on (line 9, hither)
- scan that line looking for
.map
- look at the variable/expression/any immediately before the
.map
and be very suspicious of it.
Once you know which variable to look at, you lot can read through the function looking for where information technology comes from, and whether it'southward initialized.
In our niggling example, the only other occurrence of items
is line 4:
This defines the variable simply it doesn't gear up it to anything, which means its value is undefined
. At that place's the problem. Set up that, and you fix the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a simple mistake, and it'due south colocated very shut to the site of the error. These ones are the easiest to set up!
There are a ton of potential causes for an mistake like this, though.
Maybe items
is a prop passed in from the parent component – and you lot forgot to pass it down.
Or mayhap yous did pass that prop, only the value being passed in is actually undefined or null.
If information technology's a local state variable, peradventure you're initializing the land every bit undefined – useState()
, written like that with no arguments, will exercise exactly this!
If information technology's a prop coming from Redux, maybe your mapStateToProps
is missing the value, or has a typo.
Whatever the case, though, the procedure is the same: outset 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 information technology's undefined.
You'll get it stock-still! Good luck :)
Success! At present check your electronic mail.
Learning React tin can be a struggle — and then many libraries and tools!
My advice? Ignore all of them :)
For a footstep-by-pace approach, check out my Pure React workshop.
Acquire to think in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
First learning Pure React at present
Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'chiliad a React trainer in London and would thoroughly recommend this to all front finish devs wanting to upskill or consolidate.
harrisprityruccon.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Webpack Typeerror: Cannot Read Property '0' of Undefined"
Post a Comment