Cannot Read Property 'offsetwidth' of Undefined Chart.js React
Got an error like this in your React component?
Cannot read property `map` of undefined
In this post we'll talk most how to fix this ane specifically, and along the mode you lot'll learn how to approach fixing errors in full general.
Nosotros'll cover how to read a stack trace, how to interpret the text of the error, and ultimately how to fix it.
The Quick Set up
This mistake ordinarily means you lot're trying to apply .map on an array, only that array isn't defined nonetheless.
That'due south often because the assortment is a piece of undefined land or an undefined prop.
Brand sure to initialize the state properly. That ways if it will somewhen exist an array, utilise useState([]) instead of something similar useState() or useState(zip).
Permit's look at how we can translate an error message and track down where it happened and why.
How to Find the Fault
First order of business is to figure out where the error is.
If you're using Create React App, it probably threw upward a screen like this:
TypeError
Cannot read property 'map' of undefined
App
6 | render (
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> 9 | {items . map((particular) => (
| ^
x | < div fundamental = {detail . id} >
11 | {item . proper name}
12 | < / div > Expect for the file and the line number first.
Here, that's /src/App.js and line 9, taken from the light greyness text higher up the code cake.
btw, when yous see something like /src/App.js:9:13, 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 demand to read the stack trace to figure out where the error was.
These always look long and intimidating, only the trick is that usually you can ignore most of information technology!
The lines are in order of execution, with the most recent kickoff.
Hither's the stack trace for this fault, 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.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 $1 (react-dom.development.js:16114) at performUnitOfWork (react-dom.evolution.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.evolution.js:17211) at eval (react-dom.evolution.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 G.evaluate (transpiled-module.js:692) at exist.evaluateTranspiledModule (manager.js:286) at exist.evaluateModule (manager.js:257) at compile.ts:717 at 50 (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.eastward. < computed > [equally next] (runtime.js:97) at t (asyncToGenerator.js:iii) at i (asyncToGenerator.js:25) I wasn't kidding when I said you could ignore nearly of information technology! The kickoff 2 lines are all we intendance nearly here.
The first line is the error bulletin, and every line after that spells out the unwound stack of office calls that led to it.
Let's decode a couple of these lines:
Here we accept:
-
Appis the name of our component function -
App.jsis the file where it appears -
9is the line of that file where the error occurred
Permit's expect at another one:
at performSyncWorkOnRoot (react-dom.development.js:15008) -
performSyncWorkOnRootis the proper noun of the function 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 just I wanted to state it explictly: when y'all're looking at a stack trace, you can almost e'er ignore whatever lines that refer to files that are outside your codebase, like ones from a library.
Usually, that ways yous'll pay attention to merely the first few lines.
Scan downwards the list until it starts to veer into file names you don't recognize.
In that location are some cases where y'all do intendance about the full stack, only they're few and far betwixt, in my feel. Things like… if yous suspect a issues in the library you're using, or if you recollect some erroneous input is making its fashion into library code and blowing up.
The vast majority of the time, though, the bug will be in your ain code ;)
Follow the Clues: How to Diagnose the Fault
And then the stack trace told us where to await: line 9 of App.js. Allow's open up that up.
Here's the full text of that file:
import "./styles.css" ; export default part App () { let items ; render ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div central = { item .id } > { item .name } </ div > )) } </ div > ) ; } Line 9 is this one:
And but for reference, hither's that error message again:
TypeError: Cannot read property 'map' of undefined Allow'southward break this down!
-
TypeErroris the kind of error
There are a handful of built-in mistake types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid blazon." (this part is, IMO, the least useful office of the error message)
-
Cannot read propertymeans the lawmaking was trying to read a property.
This is a practiced clue! There are only a few ways to read properties in JavaScript.
The nearly common is probably the . operator.
As in user.proper noun, to admission the name property of the user object.
Or items.map, to access the map belongings of the items object.
There's also brackets (aka square brackets, []) for accessing items in an array, similar items[5] or items['map'].
You might wonder why the error isn't more specific, like "Cannot read function `map` of undefined" – but call up, the JS interpreter has no thought what nosotros meant that blazon to be. It 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 another great clue. Combined with the previous scrap, you can be pretty sure you should exist looking for .map somewhere on this line.
-
of undefinedis a clue about the value of the variable
It would be mode more useful if the fault could say "Cannot read property `map` of items". Sadly it doesn't say that. Information technology tells you the value of that variable instead.
So at present yous can slice this all together:
- find the line that the error occurred on (line 9, hither)
- scan that line looking for
.map - expect at the variable/expression/whatever immediately before the
.mapand be very suspicious of it.
Once you know which variable to look at, y'all can read through the role looking for where it comes from, and whether information technology's initialized.
In our piffling example, the only other occurrence of items is line 4:
This defines the variable just information technology doesn't set up it to anything, which ways its value is undefined. There's the trouble. Gear up that, and y'all gear up the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a simple fault, and it'due 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 fault like this, though.
Maybe items is a prop passed in from the parent component – and y'all forgot to laissez passer it downwardly.
Or maybe you did pass that prop, simply the value being passed in is actually undefined or cypher.
If it's a local state variable, maybe you're initializing the state as undefined – useState(), written like that with no arguments, will do exactly this!
If it'southward a prop coming from Redux, mayhap your mapStateToProps is missing the value, or has a typo.
Whatever the case, though, the process is the same: offset where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and figure out why it'southward undefined.
You'll go information technology stock-still! 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-pace arroyo, check out my Pure React workshop.
Learn to call up 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/
0 Response to "Cannot Read Property 'offsetwidth' of Undefined Chart.js React"
Post a Comment