Svg Append G Cannot Read Property Append of Undefined
Got an mistake similar this in your React component?
Cannot read property `map` of undefined
In this post we'll talk about how to prepare this one specifically, and forth the style yous'll learn how to arroyo fixing errors in full general.
We'll cover how to read a stack trace, how to translate the text of the error, and ultimately how to fix information technology.
The Quick Ready
This error usually means y'all're trying to use .map
on an array, but that array isn't defined yet.
That'south frequently because the array is a piece of undefined state or an undefined prop.
Make certain to initialize the state properly. That means if it will eventually exist an array, use useState([])
instead of something like useState()
or useState(null)
.
Allow'southward await at how we can interpret an error bulletin and track down where it happened and why.
How to Find the Fault
Get-go order of business organization is to figure out where the fault is.
If you're using Create React App, information technology probably threw upwards a screen similar this:
TypeError
Cannot read property 'map' of undefined
App
six | return (
7 | < div className = "App" >
viii | < h1 > Listing of Items < / h1 >
> ix | {items . map((item) => (
| ^
ten | < div key = {item . id} >
11 | {item . name}
12 | < / div >
Look for the file and the line number outset.
Here, that'southward /src/App.js and line 9, taken from the light greyness text above the lawmaking block.
btw, when you meet something similar /src/App.js:9:13
, the mode to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If yous're looking at the browser console instead, you'll demand to read the stack trace to figure out where the error was.
These always look long and intimidating, but the flim-flam is that usually you lot can ignore most of it!
The lines are in order of execution, with the most contempo offset.
Hither'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: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.development.js:2770) at invokeGuardedCallback (react-dom.evolution.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.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.evolution.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 Thousand.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (managing director.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.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 2 lines are all nosotros intendance about here.
The first line is the fault bulletin, and every line later on that spells out the unwound stack of function calls that led to it.
Let's decode a couple of these lines:
Here we take:
-
App
is the name of our component function -
App.js
is the file where information technology appears -
9
is the line of that file where the error occurred
Let'due south look at another one:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the function where this happened -
react-dom.evolution.js
is the file -
15008
is the line number (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to land information technology explictly: when you're looking at a stack trace, you can almost always ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.
Normally, that means you'll pay attention to only the first few lines.
Scan down the list until information technology starts to veer into file names you don't recognize.
At that place are some cases where yous practise care about the full stack, only they're few and far between, in my experience. Things like… if you suspect a bug in the library you're using, or if y'all recollect some erroneous input is making its manner into library code and bravado up.
The vast majority of the time, though, the issues will be in your own code ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told united states of america where to await: line 9 of App.js. Let's open that upward.
Here's the full 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 cardinal = { particular .id } > { item .proper name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And simply for reference, here's that error bulletin again:
TypeError: Cannot read belongings 'map' of undefined
Let'due south suspension this down!
-
TypeError
is the kind of mistake
In that location are a handful of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid type." (this part is, IMO, the least useful role of the mistake message)
-
Cannot read property
means the code was trying to read a holding.
This is a practiced inkling! In that location are but a few ways to read properties in JavaScript.
The most common is probably the .
operator.
Every bit in user.name
, to admission the name
holding of the user
object.
Or items.map
, to access the map
property of the items
object.
There's also brackets (aka square brackets, []
) for accessing items in an array, like items[5]
or items['map']
.
You might wonder why the fault isn't more specific, similar "Cannot read office `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. Information technology didn't get that far, because items
is undefined.
-
'map'
is the property the lawmaking was trying to read
This one is some other slap-up inkling. Combined with the previous bit, you tin can be pretty sure yous should be looking for .map
somewhere on this line.
-
of undefined
is a clue about the value of the variable
Information technology would be way more than useful if the fault could say "Cannot read holding `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
So now you lot tin can piece this all together:
- find the line that the fault occurred on (line 9, hither)
- browse that line looking for
.map
- look at the variable/expression/whatever immediately before the
.map
and be very suspicious of it.
In one case y'all know which variable to wait at, you lot can read through the function looking for where it comes from, and whether it'due south initialized.
In our lilliputian instance, the simply other occurrence of items
is line 4:
This defines the variable simply it doesn't ready it to annihilation, which means its value is undefined
. At that place'southward the problem. Set up that, and yous fix the error!
Fixing This in the Existent World
Of course this example is tiny and contrived, with a uncomplicated mistake, and it'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 like this, though.
Maybe items
is a prop passed in from the parent component – and you forgot to pass information technology down.
Or maybe yous did pass that prop, but the value being passed in is really undefined or null.
If information technology's a local state variable, maybe you're initializing the state as undefined – useState()
, written like that with no arguments, will practise exactly this!
If information technology's a prop coming from Redux, perchance 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 use the debugger to audit the intermediate values and effigy out why it's undefined.
You lot'll get it fixed! Good luck :)
Success! Now check your email.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-stride approach, check out my Pure React workshop.
Learn to recall in React
- 90+ screencast lessons
- Total transcripts and airtight captions
- All the code from the lessons
- Developer interviews
Beginning learning Pure React at present
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 front finish devs wanting to upskill or consolidate.
avitiawhissely1974.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Svg Append G Cannot Read Property Append of Undefined"
Post a Comment