Angular 5 Cannot Read Property 'controls' of Undefined
Got an error like this in your React component?
Cannot read property `map` of undefined
In this post we'll talk about how to fix this one specifically, and along the style you'll learn 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 information technology.
The Quick Fix
This fault unremarkably means you're trying to use .map on an array, simply that array isn't defined notwithstanding.
That'southward often because the array is a piece of undefined land or an undefined prop.
Make sure to initialize the state properly. That means if information technology volition somewhen 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 down where it happened and why.
How to Observe the Error
First order of business organization is to figure out where the error is.
If you're using Create React App, it probably threw upwardly a screen like this:
TypeError
Cannot read property 'map' of undefined
App
half dozen | return (
7 | < div className = "App" >
8 | < h1 > Listing of Items < / h1 >
> nine | {items . map((detail) => (
| ^
10 | < div key = {item . id} >
11 | {item . name}
12 | < / div > Expect for the file and the line number first.
Hither, that'south /src/App.js and line 9, taken from the light greyness text higher up the code block.
btw, when yous encounter something like /src/App.js:9:13, the mode 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 figure out where the fault was.
These always look long and intimidating, simply the trick is that usually yous can ignore most of it!
The lines are in order of execution, with the almost recent first.
Here's the stack trace for this error, with the only important lines highlighted:
TypeError: Cannot read holding 'map' of undefined at App (App.js:9) at renderWithHooks (react-dom.development.js:10021) at mountIndeterminateComponent (react-dom.evolution.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.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.evolution.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.development.js:17609) at Object.return (react-dom.development.js:17672) at evaluate (index.js:7) at z (eval.js:42) at G.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.e. < computed > [as 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 most of it! The offset ii lines are all we care well-nigh hither.
The first line is the mistake bulletin, and every line after that spells out the unwound stack of part calls that led to it.
Permit's decode a couple of these lines:
Hither we have:
-
Appis the proper noun of our component part -
App.jsis the file where it appears -
9is the line of that file where the error occurred
Allow's look at another 1:
at performSyncWorkOnRoot (react-dom.development.js:15008) -
performSyncWorkOnRootis the name of the part where this happened -
react-dom.development.jsis the file -
15008is the line number (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this merely I wanted to land it explictly: when you're looking at a stack trace, you can nearly ever ignore any lines that refer to files that are outside your codebase, similar ones from a library.
Usually, that means yous'll pay attention to only the first few lines.
Scan down the listing until information technology starts to veer into file names you don't recognize.
At that place are some cases where you do intendance nigh the full stack, but they're few and far between, in my feel. Things like… if you suspect a problems in the library you're using, or if you think some erroneous input is making its way into library code and blowing up.
The vast majority of the time, though, the bug volition be in your own lawmaking ;)
Follow the Clues: How to Diagnose the Error
Then the stack trace told us where to wait: line ix of App.js. Allow's open that upwards.
Here's the full text of that file:
import "./styles.css" ; export default function App () { allow items ; return ( < div className = "App" > < h1 > Listing of Items </ h1 > { items . map ( detail => ( < div key = { item .id } > { item .name } </ div > )) } </ div > ) ; } Line nine is this ane:
And just for reference, here'southward that error message again:
TypeError: Cannot read property 'map' of undefined Let's break this downwardly!
-
TypeErroris the kind of error
There are a handful of congenital-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 to the lowest degree useful part of the mistake message)
-
Cannot read propertyways the code was trying to read a property.
This is a good clue! In that location are merely a few means to read properties in JavaScript.
The most common is probably the . operator.
As in user.name, to access the name property of the user object.
Or items.map, to access the map property of the items object.
There's besides 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, similar "Cannot read function `map` of undefined" – but think, the JS interpreter has no idea what we meant that type to be. It doesn't know information technology was supposed to be an array, or that map is a function. It didn't become that far, considering items is undefined.
-
'map'is the property the lawmaking was trying to read
This one is another great clue. Combined with the previous fleck, you can exist pretty sure you should be looking for .map somewhere on this line.
-
of undefinedis a clue about the value of the variable
It would be way more useful if the error could say "Cannot read belongings `map` of items". Sadly it doesn't say that. It 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 9, here)
- browse that line looking for
.map - look at the variable/expression/any immediately before the
.mapand be very suspicious of it.
In one case you know which variable to look at, you can read through the role looking for where it comes from, and whether it'due south initialized.
In our little instance, the simply other occurrence of items is line four:
This defines the variable but it doesn't set information technology to anything, which ways its value is undefined. At that place's the problem. Gear up that, and y'all fix the mistake!
Fixing This in the Real World
Of course this example is tiny and contrived, with a elementary fault, 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 similar this, though.
Maybe items is a prop passed in from the parent component – and you forgot to pass it down.
Or possibly you lot did pass that prop, only the value being passed in is really undefined or null.
If it's a local land variable, maybe yous're initializing the state as undefined – useState(), written like that with no arguments, volition do exactly this!
If information technology'south a prop coming from Redux, perchance your mapStateToProps is missing the value, or has a typo.
Whatsoever the instance, though, the procedure is the same: commencement where the fault is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouth or utilise the debugger to inspect the intermediate values and effigy out why it's undefined.
You'll get it fixed! Good luck :)
Success! At present check your email.
Learning React can be a struggle — so many libraries and tools!
My communication? Ignore all of them :)
For a pace-by-footstep approach, cheque out my Pure React workshop.
Larn to remember 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'due south 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 end devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
Post a Comment for "Angular 5 Cannot Read Property 'controls' of Undefined"