Cannot Read Property 'el' of Undefined Ima Sdk
Got an fault like this in your React component?
Cannot read belongings `map` of undefined
In this post nosotros'll talk about how to fix this one specifically, and along the way you'll learn how to approach fixing errors in general.
Nosotros'll embrace how to read a stack trace, how to interpret the text of the mistake, and ultimately how to fix it.
The Quick Fix
This error usually means yous're trying to employ .map
on an array, just that array isn't divers however.
That'south oftentimes considering the array is a piece of undefined land or an undefined prop.
Make sure to initialize the state properly. That means if information technology will eventually be an array, use useState([])
instead of something like useState()
or useState(null)
.
Let's look at how we can interpret an error message and track downward where it happened and why.
How to Detect the Mistake
First order of business organization is to effigy out where the error is.
If you're using Create React App, it probably threw up a screen like this:
TypeError
Cannot read property 'map' of undefined
App
6 | return (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> ix | {items . map((item) => (
| ^
10 | < div key = {item . id} >
11 | {item . proper noun}
12 | < / div >
Look for the file and the line number first.
Here, that'south /src/App.js and line 9, taken from the low-cal grayness text to a higher place the code block.
btw, when you see something similar /src/App.js:9:thirteen
, the manner to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If you lot're looking at the browser console instead, you lot'll demand to read the stack trace to effigy out where the error was.
These e'er look long and intimidating, but the flim-flam is that unremarkably yous tin can ignore near of it!
The lines are in society of execution, with the most contempo first.
Hither'due south the stack trace for this error, with the only important lines highlighted:
TypeError: Cannot read belongings '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.evolution.js:2746) at Object.invokeGuardedCallbackDev (react-dom.development.js:2770) at invokeGuardedCallback (react-dom.evolution.js:2804) at beginWork $1 (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.evolution.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.return (react-dom.development.js:17672) at evaluate (alphabetize.js:vii) at z (eval.js:42) at G.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (manager.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 > [as next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25)
I wasn't kidding when I said you lot could ignore most of it! The first ii lines are all we care nigh here.
The first line is the error message, and every line after that spells out the unwound stack of function calls that led to information technology.
Let'southward decode a couple of these lines:
Here we have:
-
App
is the name of our component role -
App.js
is the file where information technology appears -
9
is the line of that file where the error occurred
Let's look 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 (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to country information technology explictly: when you're looking at a stack trace, yous can almost ever ignore any lines that refer to files that are outside your codebase, similar ones from a library.
Usually, that means you'll pay attention to only the first few lines.
Scan downwardly the listing until information technology starts to veer into file names you don't recognize.
At that place are some cases where y'all practise intendance about the full stack, but they're few and far between, in my experience. Things like… if you suspect a bug in the library y'all're using, or if you think some erroneous input is making its way into library code and blowing upwards.
The vast majority of the time, though, the bug will be in your ain code ;)
Follow the Clues: How to Diagnose the Error
And so the stack trace told us where to look: line 9 of App.js. Allow'south open up that up.
Here'southward 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 = { item .id } > { item .name } </ div > )) } </ div > ) ; }
Line 9 is this ane:
And just for reference, here'due south that error bulletin over again:
TypeError: Cannot read property 'map' of undefined
Permit's break this down!
-
TypeError
is the kind of error
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 not of a valid type." (this part is, IMO, the least useful role of the mistake message)
-
Cannot read property
ways the code was trying to read a property.
This is a good clue! There are only a few ways to read properties in JavaScript.
The nearly common is probably the .
operator.
Equally in user.name
, to access the proper noun
property 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[5]
or items['map']
.
You might wonder why the fault isn't more specific, like "Cannot read function `map` of undefined" – but call up, the JS interpreter has no thought what nosotros meant that type to be. Information technology doesn't know information technology was supposed to be an array, or that map
is a function. It didn't get that far, considering items
is undefined.
-
'map'
is the property the lawmaking was trying to read
This one is another nifty clue. Combined with the previous bit, you lot can be pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue about 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 can piece this all together:
- find the line that the error occurred on (line ix, here)
- scan that line looking for
.map
- expect at the variable/expression/whatever immediately before the
.map
and be very suspicious of it.
Once yous know which variable to look at, you tin read through the role looking for where it comes from, and whether it's initialized.
In our footling case, the only other occurrence of items
is line 4:
This defines the variable only information technology doesn't set it to annihilation, which means its value is undefined
. In that location's the trouble. Fix that, and yous fix the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a unproblematic error, and information technology's colocated very shut to the site of the mistake. These ones are the easiest to ready!
There are a ton of potential causes for an error like this, though.
Peradventure items
is a prop passed in from the parent component – and you forgot to laissez passer it down.
Or maybe you did pass that prop, just the value beingness passed in is really undefined or zip.
If it'southward a local state variable, maybe yous're initializing the country as undefined – useState()
, written like that with no arguments, will practise 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 fault is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
due south or employ the debugger to inspect the intermediate values and figure out why it's undefined.
You'll get it fixed! Good luck :)
Success! Now cheque your email.
Learning React tin can be a struggle — and 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 closed captions
- All the code from the lessons
- Developer interviews
Kickoff learning Pure React at present
Dave Ceddia'south Pure React is a piece of work of enormous clarity and depth. Hats off. I'yard a React trainer in London and would thoroughly recommend this to all front end end devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Cannot Read Property 'el' of Undefined Ima Sdk"
Postar um comentário