Typeerror: Cannot Read Property 'preparestyles' of Undefined Raisedbutton
Got an error like this in your React component?
Cannot read property `map` of undefined
In this post we'll talk about how to ready this one specifically, and along the mode yous'll acquire how to approach fixing errors in 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 Fix
This error commonly means you're trying to use .map
on an array, only that array isn't defined however.
That's often because the array is a piece of undefined country or an undefined prop.
Make sure to initialize the state properly. That means if it will somewhen be an array, employ useState([])
instead of something like useState()
or useState(nil)
.
Let's wait at how nosotros can interpret an mistake message and track down where information technology happened and why.
How to Observe the Error
Beginning gild of business organisation is to effigy out where the error is.
If you're using Create React App, information technology 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} >
eleven | {item . name}
12 | < / div >
Await for the file and the line number showtime.
Here, that's /src/App.js and line 9, taken from the light greyness text above the code cake.
btw, when you see something like /src/App.js:ix:13
, the style to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If yous're looking at the browser console instead, you'll need to read the stack trace to effigy out where the error was.
These e'er expect long and intimidating, but the trick is that usually you tin ignore most of it!
The lines are in order of execution, with the most contempo first.
Here'southward the stack trace for this error, with the simply important lines highlighted:
TypeError: Cannot read property 'map' of undefined at App (App.js:nine) at renderWithHooks (react-dom.evolution.js:10021) at mountIndeterminateComponent (react-dom.development.js:12143) at beginWork (react-dom.evolution.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 $ane (react-dom.evolution.js:16114) at performUnitOfWork (react-dom.development.js:15339) at workLoopSync (react-dom.evolution.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.development.js:15104) at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609) at Object.render (react-dom.development.js:17672) at evaluate (index.js:vii) at z (eval.js:42) at One thousand.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (manager.js:286) at be.evaluateModule (director.js:257) at compile.ts:717 at fifty (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 get-go 2 lines are all we intendance about here.
The first line is the error message, and every line afterwards that spells out the unwound stack of office calls that led to it.
Let'south decode a couple of these lines:
Here nosotros take:
-
App
is the name of our component function -
App.js
is the file where it appears -
nine
is the line of that file where the mistake occurred
Let'south look at another i:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the proper name of the part where this happened -
react-dom.development.js
is the file -
15008
is the line number (it'southward a big file!)
Ignore Files That Aren't Yours
I already mentioned this merely I wanted to state information technology explictly: when you're looking at a stack trace, you can almost always ignore any lines that refer to files that are exterior your codebase, like ones from a library.
Unremarkably, that means you'll pay attention to but the kickoff few lines.
Browse down the list until it starts to veer into file names you don't recognize.
There are some cases where you do care virtually the full stack, but they're few and far between, in my experience. Things like… if yous doubtable a issues in the library y'all're using, or if yous think some erroneous input is making its way into library code and blowing up.
The vast bulk of the time, though, the bug will exist in your ain lawmaking ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told the states where to look: line ix of App.js. Let's open that upwardly.
Here'due south the full text of that file:
import "./styles.css" ; consign default function App () { let items ; return ( < div className = "App" > < h1 > Listing of Items </ h1 > { items . map ( item => ( < div key = { particular .id } > { item .proper name } </ div > )) } </ div > ) ; }
Line 9 is this 1:
And only for reference, hither's that error bulletin once more:
TypeError: Cannot read belongings 'map' of undefined
Let'due south pause this downwardly!
-
TypeError
is the kind of error
At that place 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 least useful part of the mistake bulletin)
-
Cannot read property
ways the code was trying to read a belongings.
This is a good inkling! There are but a few ways to read backdrop in JavaScript.
The well-nigh mutual is probably the .
operator.
Equally 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'southward likewise brackets (aka square brackets, []
) for accessing items in an array, like items[v]
or items['map']
.
Yous might wonder why the error isn't more specific, like "Cannot read part `map` of undefined" – just call back, the JS interpreter has no idea what we meant that blazon to exist. It doesn't know information technology was supposed to be an array, or that map
is a part. Information technology didn't get that far, because items
is undefined.
-
'map'
is the holding the code was trying to read
This ane is some other great clue. Combined with the previous bit, yous tin exist pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue virtually the value of the variable
It would be style more useful if the error 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 can slice this all together:
- find the line that the error occurred on (line 9, here)
- scan that line looking for
.map
- look at the variable/expression/whatever immediately earlier the
.map
and be very suspicious of it.
In one case yous know which variable to look at, you can read through the function looking for where it comes from, and whether information technology's initialized.
In our little example, the only other occurrence of items
is line 4:
This defines the variable only it doesn't ready it to anything, which means its value is undefined
. At that place's the problem. Gear up 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 shut 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.
Perchance items
is a prop passed in from the parent component – and you forgot to pass information technology downward.
Or maybe yous did laissez passer that prop, but the value existence passed in is really undefined or null.
If it's a local land variable, perchance you're initializing the land every bit undefined – useState()
, written similar that with no arguments, volition do exactly this!
If information technology'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 aforementioned: start where the error is and work backwards, verifying your assumptions at each signal the variable is used. Throw in some console.log
southward or use the debugger to audit the intermediate values and effigy 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 so many libraries and tools!
My advice? Ignore all of them :)
For a step-past-step approach, check out my Pure React workshop.
Acquire to recollect in React
- ninety+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Start 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 devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
Post a Comment for "Typeerror: Cannot Read Property 'preparestyles' of Undefined Raisedbutton"