Uncaught Typeerror: Cannot Read Property 'createdocumentfragment' of Undefined
Got an error similar this in your React component?
Cannot read holding `map` of undefined
In this post nosotros'll talk about how to fix this one specifically, and along the fashion you lot'll larn how to approach fixing errors in general.
We'll cover how to read a stack trace, how to translate the text of the error, and ultimately how to prepare information technology.
The Quick Fix
This error usually means you're trying to apply .map
on an array, but that array isn't defined yet.
That's often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the state properly. That means if it volition eventually be an assortment, apply useState([])
instead of something similar useState()
or useState(nada)
.
Let'due south look at how nosotros tin can interpret an error bulletin and rail downwardly where it happened and why.
How to Observe the Error
First social club of business organization is to effigy out where the error is.
If you're using Create React App, it probably threw upwards a screen like this:
TypeError
Cannot read property 'map' of undefined
App
6 | return (
vii | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
ten | < div key = {detail . id} >
11 | {particular . name}
12 | < / div >
Await for the file and the line number get-go.
Here, that's /src/App.js and line 9, taken from the light greyness text above the lawmaking block.
btw, when you see something like /src/App.js:9:thirteen
, 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 figure out where the error was.
These always await long and intimidating, but the trick is that usually you can ignore near of it!
The lines are in order of execution, with the most recent showtime.
Here'due south the stack trace for this error, with the only of import 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 $i (react-dom.evolution.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.development.js:14770) at updateContainer (react-dom.evolution.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 (index.js:7) at z (eval.js:42) at Yard.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (manager.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.east. < computed > [equally 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 outset 2 lines are all we care almost here.
The first line is the error message, and every line after that spells out the unwound stack of function calls that led to it.
Let's decode a couple of these lines:
Hither we have:
-
App
is the name of our component function -
App.js
is the file where information technology appears -
ix
is the line of that file where the error occurred
Let's look at another one:
at performSyncWorkOnRoot (react-dom.development.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's a big file!)
Ignore Files That Aren't Yours
I already mentioned this simply I wanted to state information technology explictly: when you're looking at a stack trace, you tin nigh always ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.
Commonly, that ways you'll pay attention to only the first few lines.
Scan down the list until it starts to veer into file names you don't recognize.
At that place are some cases where you lot exercise care nigh the total stack, but they're few and far between, in my feel. Things like… if y'all suspect a issues in the library yous're using, or if y'all think some erroneous input is making its way into library code and blowing up.
The vast bulk of the time, though, the bug will be in your own code ;)
Follow the Clues: How to Diagnose the Error
And so the stack trace told us where to look: line nine of App.js. Let's open that upward.
Here'southward the total text of that file:
import "./styles.css" ; export default function App () { let items ; return ( < div className = "App" > < h1 > Listing of Items </ h1 > { items . map ( item => ( < div key = { detail .id } > { item .name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And merely for reference, here's that error message again:
TypeError: Cannot read belongings 'map' of undefined
Let's break this downwardly!
-
TypeError
is the kind of fault
There are a scattering of congenital-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 office of the fault message)
-
Cannot read property
means the lawmaking was trying to read a property.
This is a good inkling! There are just a few ways to read properties in JavaScript.
The nearly common is probably the .
operator.
As in user.name
, to admission the name
property of the user
object.
Or items.map
, to admission the map
belongings of the items
object.
There'southward also brackets (aka foursquare brackets, []
) for accessing items in an array, like items[v]
or items['map']
.
You lot might wonder why the error isn't more specific, like "Cannot read function `map` of undefined" – but remember, the JS interpreter has no idea what we meant that blazon to be. It doesn't know it was supposed to exist an assortment, or that map
is a function. It didn't get that far, because items
is undefined.
-
'map'
is the holding the code was trying to read
This one is some other great clue. Combined with the previous bit, you tin can exist pretty sure you lot should be looking for .map
somewhere on this line.
-
of undefined
is a inkling nigh the value of the variable
It would be way more useful if the error could say "Cannot read property `map` of items". Sadly information technology doesn't say that. Information technology tells you the value of that variable instead.
So now you tin piece this all together:
- find the line that the error occurred on (line 9, here)
- scan that line looking for
.map
- look at the variable/expression/whatever immediately before the
.map
and be very suspicious of it.
One time you know which variable to look at, you can read through the office looking for where information technology comes from, and whether it's initialized.
In our little example, the simply other occurrence of items
is line four:
This defines the variable but it doesn't gear up it to anything, which means its value is undefined
. In that location's the trouble. Prepare that, and yous fix the fault!
Fixing This in the Real World
Of course this instance is tiny and contrived, with a simple fault, and it's colocated very shut to the site of the fault. These ones are the easiest to fix!
In that location are a ton of potential causes for an error like this, though.
Maybe items
is a prop passed in from the parent component – and y'all forgot to pass it down.
Or maybe you did pass that prop, simply the value existence passed in is actually undefined or null.
If it's a local state variable, maybe you're initializing the state as undefined – useState()
, written similar that with no arguments, will do exactly this!
If it's a prop coming from Redux, maybe your mapStateToProps
is missing the value, or has a typo.
Whatever the case, though, the process 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
s or utilize the debugger to inspect the intermediate values and effigy out why it'southward undefined.
You'll get it fixed! Good luck :)
Success! Now bank check your email.
Learning React can be a struggle — so many libraries and tools!
My communication? Ignore all of them :)
For a step-by-step approach, check out my Pure React workshop.
Learn to think in React
- xc+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Offset learning Pure React now
Dave Ceddia'due south Pure React is a piece of work of enormous clarity and depth. Hats off. I'thousand a React trainer in London and would thoroughly recommend this to all front stop devs wanting to upskill or consolidate.
whitehousenoung1987.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
Postar um comentário for "Uncaught Typeerror: Cannot Read Property 'createdocumentfragment' of Undefined"