Uncaught Typeerror: Cannot Read Property 'clearrect' of Undefined
Got an fault 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 along the fashion you lot'll learn how to approach fixing errors in general.
We'll encompass how to read a stack trace, how to interpret the text of the error, and ultimately how to set it.
The Quick Gear up
This error usually ways you lot're trying to use .map on an array, but that array isn't defined withal.
That's often because the array is a piece of undefined land or an undefined prop.
Make sure to initialize the land properly. That means if it volition eventually be an array, use useState([]) instead of something like useState() or useState(cipher).
Let'south expect at how we tin can interpret an fault message and track down where it happened and why.
How to Observe the Fault
Commencement order of business is to figure out where the fault 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 >
> 9 | {items . map((item) => (
| ^
10 | < div key = {item . id} >
11 | {detail . name}
12 | < / div > Await for the file and the line number first.
Here, that'south /src/App.js and line 9, taken from the light gray text above the code block.
btw, when you meet something like /src/App.js:nine:13, the way to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If y'all're looking at the browser console instead, yous'll need to read the stack trace to effigy out where the error was.
These always look long and intimidating, but the play tricks is that usually you tin ignore most of it!
The lines are in society of execution, with the virtually contempo offset.
Here's the stack trace for this error, with the simply important lines highlighted:
TypeError: Cannot read belongings '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.development.js:2770) at invokeGuardedCallback (react-dom.development.js:2804) at beginWork $i (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.evolution.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.development.js:17672) at evaluate (alphabetize.js:7) at z (eval.js:42) at One thousand.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (manager.js:286) at be.evaluateModule (manager.js:257) at compile.ts:717 at 50 (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.due east. < computed > [every bit next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25) I wasn't kidding when I said you could ignore about of it! The first 2 lines are all we care virtually hither.
The outset line is the error message, and every line subsequently that spells out the unwound stack of office calls that led to it.
Allow's decode a couple of these lines:
Hither we have:
-
Appis the name of our component function -
App.jsis the file where information technology appears -
ixis the line of that file where the error occurred
Let'southward await at another one:
at performSyncWorkOnRoot (react-dom.development.js:15008) -
performSyncWorkOnRootis the proper noun of the function where this happened -
react-dom.evolution.jsis the file -
15008is the line number (it'due south a big file!)
Ignore Files That Aren't Yours
I already mentioned this only I wanted to state it explictly: when you're looking at a stack trace, you lot can almost always ignore whatsoever lines that refer to files that are exterior your codebase, like ones from a library.
Usually, that means you'll pay attention to only the kickoff few lines.
Scan downwardly the listing until it starts to veer into file names you don't recognize.
There are some cases where you practice care about the full stack, but they're few and far between, in my experience. Things like… if you lot doubtable 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 up.
The vast majority of the time, though, the problems will be in your own code ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told us where to look: line nine of App.js. Allow'southward open up that up.
Hither'south the full text of that file:
import "./styles.css" ; export default function App () { let items ; return ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div key = { particular .id } > { particular .name } </ div > )) } </ div > ) ; } Line 9 is this ane:
And just for reference, here's that error bulletin over again:
TypeError: Cannot read holding 'map' of undefined Let'south break this down!
-
TypeErroris the kind of error
There 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 function of the mistake message)
-
Cannot read propertymeans the lawmaking was trying to read a property.
This is a good clue! There are only a few means to read properties in JavaScript.
The virtually common is probably the . operator.
As in user.proper noun, to access the proper name property 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 assortment, like items[5] or items['map'].
Y'all might wonder why the error isn't more specific, similar "Cannot read function `map` of undefined" – but recall, the JS interpreter has no idea what we meant that type to be. Information technology doesn't know it was supposed to be an array, or that map is a part. It didn't get that far, because items is undefined.
-
'map'is the property the code was trying to read
This one is some other bully inkling. Combined with the previous bit, you tin can exist pretty certain you lot should be looking for .map somewhere on this line.
-
of undefinedis a clue virtually the value of the variable
It would exist way more useful if the mistake could say "Cannot read property `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
So now you tin can piece this all together:
- find the line that the error occurred on (line ix, here)
- scan 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 expect at, you can read through the function looking for where it comes from, and whether it'southward initialized.
In our footling example, the only other occurrence of items is line 4:
This defines the variable but it doesn't set it to anything, which ways its value is undefined. There'southward 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 simple mistake, and it's colocated very close to the site of the error. These ones are the easiest to prepare!
There are a ton of potential causes for an error like this, though.
Possibly items is a prop passed in from the parent component – and you forgot to pass information technology downwardly.
Or maybe you did pass that prop, but the value beingness passed in is really undefined or null.
If it's a local state variable, maybe you're initializing the country every bit undefined – useState(), written like that with no arguments, will do exactly this!
If information technology'southward a prop coming from Redux, maybe your mapStateToProps is missing the value, or has a typo.
Whatsoever the case, though, the process is the same: start where the mistake is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or apply the debugger to inspect the intermediate values and figure out why it'south undefined.
You'll get it fixed! Skillful luck :)
Success! At present check your electronic mail.
Learning React tin be a struggle — and 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 think in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Kickoff learning Pure React now
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.
Uncaught Typeerror: Cannot Read Property 'clearrect' of Undefined
Source: https://daveceddia.com/fix-react-errors/
Post a Comment for "Uncaught Typeerror: Cannot Read Property 'clearrect' of Undefined"