Cannot Read Property 'hoverseries' of Undefined H.destroy
Got an error like this in your React component?
Cannot read holding `map` of undefined
In this postal service we'll talk virtually how to fix this one specifically, and along the mode you'll larn how to arroyo fixing errors in 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 fault usually means you're trying to utilise .map on an array, but that array isn't defined yet.
That'south often because the array is a slice of undefined state or an undefined prop.
Brand sure to initialize the country properly. That ways if it will eventually exist an array, utilize useState([]) instead of something like useState() or useState(zilch).
Allow's await at how we can interpret an error bulletin and track downwards where information technology happened and why.
How to Find the Mistake
First order of business is to figure out where the error is.
If you lot're using Create React App, it probably threw upward a screen similar this:
TypeError
Cannot read property 'map' of undefined
App
half dozen | return (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> nine | {items . map((detail) => (
| ^
10 | < div primal = {item . id} >
11 | {item . name}
12 | < / div > Await for the file and the line number first.
Here, that'southward /src/App.js and line 9, taken from the calorie-free gray text above the code cake.
btw, when you encounter something like /src/App.js:9:13, the fashion 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 figure out where the fault was.
These always look long and intimidating, simply the play a trick on is that normally you lot can ignore most of it!
The lines are in gild of execution, with the almost recent start.
Here'south the stack trace for this mistake, with the only of import lines highlighted:
TypeError: Cannot read property 'map' of undefined at App (App.js:9) 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.evolution.js:2804) at beginWork $1 (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.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.evolution.js:17672) at evaluate (alphabetize.js:7) at z (eval.js:42) at G.evaluate (transpiled-module.js:692) at exist.evaluateTranspiledModule (managing director.js:286) at exist.evaluateModule (manager.js:257) at compile.ts:717 at l (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.e. < computed > [equally 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 about of it! The first two lines are all nosotros care near hither.
The beginning line is the error message, and every line after that spells out the unwound stack of office calls that led to it.
Allow's decode a couple of these lines:
Hither we have:
-
Appis the name of our component function -
App.jsis the file where it appears -
9is the line of that file where the error occurred
Let'south look at another ane:
at performSyncWorkOnRoot (react-dom.development.js:15008) -
performSyncWorkOnRootis the proper noun of the part where this happened -
react-dom.evolution.jsis the file -
15008is the line number (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this simply I wanted to state it explictly: when you're looking at a stack trace, you can almost always ignore any lines that refer to files that are exterior your codebase, like ones from a library.
Usually, that means yous'll pay attention to merely the offset few lines.
Browse down the list until it starts to veer into file names yous don't recognize.
There are some cases where you do care almost the full stack, but they're few and far between, in my experience. Things similar… if you suspect a bug in the library you lot're using, or if yous call back some erroneous input is making its way 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 Mistake
And then the stack trace told us where to expect: line nine of App.js. Let's open that up.
Hither's the full text of that file:
import "./styles.css" ; export default function App () { permit items ; return ( < div className = "App" > < h1 > Listing of Items </ h1 > { items . map ( item => ( < div key = { detail .id } > { particular .name } </ div > )) } </ div > ) ; } Line 9 is this i:
And only for reference, hither's that fault bulletin again:
TypeError: Cannot read property 'map' of undefined Let's break this downward!
-
TypeErroris the kind of error
There are a handful of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful part of the error message)
-
Cannot read propertymeans the code was trying to read a property.
This is a good clue! In that location are only a few ways to read properties in JavaScript.
The most common is probably the . operator.
As in user.name, to admission the proper noun property of the user object.
Or items.map, to access the map property of the items object.
In that location'south as well brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].
You might wonder why the error isn't more specific, like "Cannot read function `map` of undefined" – only remember, the JS interpreter has no idea what nosotros meant that type to be. It doesn't know it was supposed to be an assortment, or that map is a function. It didn't go that far, because items is undefined.
-
'map'is the property the lawmaking was trying to read
This ane is another nifty clue. Combined with the previous fleck, you can be pretty sure you should be looking for .map somewhere on this line.
-
of undefinedis a inkling about the value of the variable
It would be fashion more useful if the fault could say "Cannot read property `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
And then now y'all tin slice this all together:
- find the line that the fault occurred on (line nine, here)
- scan that line looking for
.map - look at the variable/expression/whatever immediately earlier the
.mapand exist very suspicious of information technology.
Once yous know which variable to look at, you can read through the function looking for where it comes from, and whether it'southward initialized.
In our piffling example, the only other occurrence of items is line 4:
This defines the variable but it doesn't set it to anything, which means its value is undefined. There'due south the problem. Fix that, and you lot fix the error!
Fixing This in the Real Earth
Of course this instance is tiny and contrived, with a uncomplicated mistake, and information technology'south 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 similar this, though.
Maybe items is a prop passed in from the parent component – and yous forgot to pass it down.
Or perchance you did pass that prop, but the value being passed in is really undefined or null.
If it'southward a local state variable, peradventure y'all're initializing the state as undefined – useState(), written like that with no arguments, will do exactly this!
If it'southward a prop coming from Redux, peradventure your mapStateToProps is missing the value, or has a typo.
Any the case, though, the process is the same: start where the error is and piece of work backwards, verifying your assumptions at each bespeak the variable is used. Throw in some console.logsouthward or use the debugger to inspect the intermediate values and effigy out why it'south undefined.
You'll get it stock-still! 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-stride approach, bank check out my Pure React workshop.
Learn to call back 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'm a React trainer in London and would thoroughly recommend this to all front end finish devs wanting to upskill or consolidate.
palaciosbriat1956.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Cannot Read Property 'hoverseries' of Undefined H.destroy"
Post a Comment