Typeerror: Cannot Read Property 'includes' of Undefined
Got an error similar this in your React component?
Cannot read belongings `map` of undefined
In this post we'll talk about how to ready this one specifically, and along the way you'll larn how to approach fixing errors in general.
We'll cover how to read a stack trace, how to interpret the text of the mistake, and ultimately how to set it.
The Quick Fix
This mistake unremarkably means you're trying to use .map on an array, only that array isn't defined nevertheless.
That'due south often because the assortment is a piece of undefined country or an undefined prop.
Brand sure to initialize the state properly. That means if it will somewhen be an array, utilize useState([]) instead of something like useState() or useState(null).
Let'south look at how we tin interpret an fault message and track down where it happened and why.
How to Discover the Error
First order of business 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
6 | return (
7 | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> ix | {items . map((item) => (
| ^
x | < div cardinal = {item . id} >
11 | {particular . proper name}
12 | < / div > Wait for the file and the line number first.
Here, that'south /src/App.js and line nine, taken from the light grey text above the lawmaking block.
btw, when you lot see something similar /src/App.js:nine: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 lot'll need to read the stack trace to effigy out where the mistake was.
These e'er look long and intimidating, just the trick is that usually you lot tin ignore near of it!
The lines are in lodge of execution, with the almost recent first.
Here's the stack trace for this error, with the only important lines highlighted:
TypeError: Cannot read property '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.evolution.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 $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.evolution.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:7) at z (eval.js:42) at G.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (managing director.js:286) at be.evaluateModule (managing director.js:257) at compile.ts:717 at l (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.east. < computed > [as next] (runtime.js:97) at t (asyncToGenerator.js:iii) at i (asyncToGenerator.js:25) I wasn't kidding when I said you could ignore most of it! The first two lines are all nosotros care well-nigh here.
The first line is the error message, and every line later that spells out the unwound stack of part calls that led to information technology.
Allow'southward decode a couple of these lines:
Here we take:
-
Appis the proper name of our component office -
App.jsis the file where it appears -
nineis the line of that file where the error occurred
Allow's look at another one:
at performSyncWorkOnRoot (react-dom.development.js:15008) -
performSyncWorkOnRootis the proper noun of the role where this happened -
react-dom.development.jsis the file -
15008is the line number (it'south a large file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to state it explictly: when yous're looking at a stack trace, you can about always ignore any lines that refer to files that are outside your codebase, like ones from a library.
Usually, that means you lot'll pay attention to only the first few lines.
Scan down the list until it starts to veer into file names you don't recognize.
There are some cases where you do care about the total stack, but they're few and far between, in my experience. Things like… if yous suspect a bug in the library you're using, or if you call back some erroneous input is making its mode into library lawmaking and blowing upwardly.
The vast majority of the fourth dimension, though, the problems volition exist in your own code ;)
Follow the Clues: How to Diagnose the Fault
Then the stack trace told the states where to look: line ix of App.js. Let'south open that upwardly.
Hither'south the full text of that file:
import "./styles.css" ; consign default function App () { permit items ; render ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( item => ( < div central = { item .id } > { detail .name } </ div > )) } </ div > ) ; } Line 9 is this ane:
And just for reference, here's that error message again:
TypeError: Cannot read property 'map' of undefined Allow'southward break this down!
-
TypeErroris the kind of mistake
At that place are a handful of built-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 fault bulletin)
-
Cannot read propertyways 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 nearly 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 holding of the items object.
There's likewise brackets (aka square brackets, []) for accessing items in an array, similar items[5] or items['map'].
You lot might wonder why the error isn't more specific, similar "Cannot read role `map` of undefined" – but remember, the JS interpreter has no idea what we meant that type to exist. It doesn't know it was supposed to be an array, or that map is a function. It didn't become that far, because items is undefined.
-
'map'is the property the lawmaking was trying to read
This ane is another great inkling. Combined with the previous chip, you can be pretty sure yous should be looking for .map somewhere on this line.
-
of undefinedis a clue about the value of the variable
It would be manner more useful if the error could say "Cannot read property `map` of items". Sadly it doesn't say that. It tells you lot the value of that variable instead.
So now yous can piece this all together:
- find the line that the fault occurred on (line ix, here)
- browse that line looking for
.map - await at the variable/expression/whatever immediately before the
.mapand be very suspicious of it.
Once you know which variable to await at, you lot can read through the part looking for where it comes from, and whether it's initialized.
In our piddling example, the only other occurrence of items is line 4:
This defines the variable simply information technology doesn't ready it to annihilation, which means its value is undefined. There'due south the problem. Fix that, and you prepare the error!
Fixing This in the Real Globe
Of course this example is tiny and contrived, with a simple fault, and it's colocated very close to the site of the mistake. These ones are the easiest to fix!
There are a ton of potential causes for an error like this, though.
Maybe items is a prop passed in from the parent component – and yous forgot to laissez passer it down.
Or possibly you did pass that prop, only the value beingness passed in is actually undefined or zippo.
If it's a local state variable, perchance you're initializing the state as undefined – useState(), written like that with no arguments, will do exactly this!
If it's a prop coming from Redux, perchance your mapStateToProps is missing the value, or has a typo.
Whatever the case, though, the process is the same: start where the error is and work backwards, verifying your assumptions at each signal the variable is used. Throw in some console.logs or utilise the debugger to inspect the intermediate values and figure out why it's undefined.
You'll get it fixed! Practiced luck :)
Success! Now bank check your email.
Learning React tin can be a struggle — so 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 remember in React
- 90+ screencast lessons
- Total transcripts and closed captions
- All the code from the lessons
- Developer interviews
First learning Pure React now
Dave Ceddia's Pure React is a piece of 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.
mcmullinwerseemse.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Typeerror: Cannot Read Property 'includes' of Undefined"
Postar um comentário