Typeerror: Cannot Read Property 'domnodeinsertedbyjs' of Undefined
Got an mistake like this in your React component?
Cannot read belongings `map` of undefined
In this post we'll talk about how to gear up this i specifically, and along the way you'll acquire how to approach fixing errors in general.
We'll comprehend how to read a stack trace, how to interpret the text of the mistake, and ultimately how to fix it.
The Quick Set up
This error usually means you're trying to use .map
on an assortment, but that array isn't defined yet.
That's oftentimes because the array is a piece of undefined country or an undefined prop.
Make sure to initialize the land properly. That ways if it will eventually exist an assortment, use useState([])
instead of something similar useState()
or useState(null)
.
Let's look at how we tin interpret an error message and runway downwards where it happened and why.
How to Notice the Mistake
Commencement order of concern is to figure out where the error is.
If y'all're using Create React App, it probably threw up a screen like this:
TypeError
Cannot read property 'map' of undefined
App
6 | return (
seven | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div key = {item . id} >
eleven | {item . name}
12 | < / div >
Look for the file and the line number offset.
Hither, that'due south /src/App.js and line 9, taken from the light gray text in a higher place the lawmaking block.
btw, when you see something like /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 demand to read the stack trace to effigy out where the fault was.
These always look long and intimidating, but the pull a fast one on is that usually you can ignore near of it!
The lines are in order of execution, with the most contempo outset.
Hither'southward the stack trace for this mistake, 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.development.js:15339) at workLoopSync (react-dom.evolution.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.evolution.js:17609) at Object.render (react-dom.evolution.js:17672) at evaluate (alphabetize.js:7) at z (eval.js:42) at Thou.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (managing director.js:286) at exist.evaluateModule (managing director.js:257) at compile.ts:717 at l (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.e. < computed > [as next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25)
I wasn't kidding when I said you could ignore most of it! The first ii lines are all nosotros care nearly hither.
The first line is the mistake message, and every line after that spells out the unwound stack of function calls that led to it.
Let'south decode a couple of these lines:
Here nosotros have:
-
App
is the name of our component role -
App.js
is the file where it appears -
9
is the line of that file where the error occurred
Let's expect at some other 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'south a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to land it explictly: when you're looking at a stack trace, you tin near ever 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 first few lines.
Browse downward the listing until information technology starts to veer into file names you lot don't recognize.
There are some cases where you do intendance about the total stack, but they're few and far between, in my feel. Things like… if yous doubtable a problems in the library you're using, or if you think some erroneous input is making its way into library code and bravado up.
The vast majority of the time, though, the bug will exist in your own lawmaking ;)
Follow the Clues: How to Diagnose the Error
And so the stack trace told us where to wait: line 9 of App.js. Let's open up that upwardly.
Hither'south the total text of that file:
import "./styles.css" ; export default part App () { let items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div primal = { item .id } > { particular .name } </ div > )) } </ div > ) ; }
Line ix is this one:
And simply for reference, here's that error bulletin once more:
TypeError: Cannot read property 'map' of undefined
Permit'south break this down!
-
TypeError
is the kind of error
At that place 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 to the lowest degree useful part of the error message)
-
Cannot read property
ways the code was trying to read a property.
This is a skilful clue! There are only a few means to read properties in JavaScript.
The virtually mutual is probably the .
operator.
As in user.proper name
, to access the name
holding of the user
object.
Or items.map
, to access the map
property of the items
object.
There's too brackets (aka square brackets, []
) for accessing items in an array, like items[five]
or items['map']
.
You might wonder why the fault isn't more specific, like "Cannot read office `map` of undefined" – but recall, 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 part. Information technology didn't get that far, because items
is undefined.
-
'map'
is the property the lawmaking was trying to read
This one is another great inkling. Combined with the previous bit, y'all tin be pretty sure y'all should be looking for .map
somewhere on this line.
-
of undefined
is a clue most the value of the variable
Information technology would be manner 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 so now you tin can piece this all together:
- notice the line that the error occurred on (line 9, hither)
- scan that line looking for
.map
- wait at the variable/expression/whatever immediately before the
.map
and exist very suspicious of it.
Once you know which variable to look at, you tin can read through the function looking for where information technology comes from, and whether it'south initialized.
In our little example, the only other occurrence of items
is line iv:
This defines the variable but it doesn't set it to anything, which means its value is undefined
. In that location's the trouble. Fix that, and you fix the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a elementary mistake, and it'due 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 mistake like this, though.
Maybe items
is a prop passed in from the parent component – and you forgot to pass it downward.
Or peradventure yous did pass that prop, but the value beingness passed in is actually undefined or zip.
If it'due south a local country variable, perhaps y'all're initializing the state as undefined – useState()
, written like that with no arguments, will practice exactly this!
If it's a prop coming from Redux, perhaps your mapStateToProps
is missing the value, or has a typo.
Any the case, though, the procedure is the same: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
southward or utilize the debugger to inspect the intermediate values and figure out why it's undefined.
Yous'll get it stock-still! Good luck :)
Success! Now check your email.
Learning React can be a struggle — then many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, bank 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
Start learning Pure React at present
Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'one thousand 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 "Typeerror: Cannot Read Property 'domnodeinsertedbyjs' of Undefined"
Post a Comment