React Apollo Typeerror: Cannot Read Property '0' of Undefined
Got an error like this in your React component?
Cannot read property `map` of undefined
In this post we'll talk almost how to set this one specifically, and forth the fashion you lot'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 error, and ultimately how to fix it.
The Quick Fix
This error unremarkably means yous're trying to apply .map on an assortment, only that array isn't defined however.
That's often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the country properly. That means if it volition eventually be an array, utilize useState([]) instead of something like useState() or useState(goose egg).
Let's wait at how nosotros can interpret an fault message and track down where information technology happened and why.
How to Find the Error
Outset guild of business is to figure out where the fault is.
If you're using Create React App, it probably threw up a screen similar this:
TypeError
Cannot read belongings 'map' of undefined
App
6 | return (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> ix | {items . map((item) => (
| ^
10 | < div cardinal = {item . id} >
11 | {item . name}
12 | < / div > Wait for the file and the line number first.
Here, that's /src/App.js and line 9, taken from the light gray text above the code block.
btw, when you see something similar /src/App.js:9:13, the way to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If you lot're looking at the browser console instead, you'll need to read the stack trace to figure out where the error was.
These always look long and intimidating, simply the trick is that unremarkably y'all tin can ignore most of it!
The lines are in order of execution, with the most recent first.
Here'due south the stack trace for this error, with the only of import lines highlighted:
TypeError: Cannot read holding 'map' of undefined at App (App.js:nine) 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.evolution.js:2770) at invokeGuardedCallback (react-dom.development.js:2804) at beginWork $1 (react-dom.development.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.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.development.js:17609) at Object.render (react-dom.development.js:17672) at evaluate (index.js:7) at z (eval.js:42) at One thousand.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (director.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 next] (runtime.js:97) at t (asyncToGenerator.js:3) at i (asyncToGenerator.js:25) I wasn't kidding when I said you could ignore nearly of it! The first 2 lines are all we care about here.
The first line is the error message, and every line later on that spells out the unwound stack of part calls that led to it.
Permit'southward decode a couple of these lines:
Hither we have:
-
Appis the name of our component function -
App.jsis the file where it appears -
ixis the line of that file where the error occurred
Let's wait at another one:
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 (information technology'southward a big file!)
Ignore Files That Aren't Yours
I already mentioned this but I wanted to country it explictly: when you're looking at a stack trace, you can almost ever ignore any lines that refer to files that are outside your codebase, similar ones from a library.
Unremarkably, that ways you'll pay attention to only the beginning few lines.
Scan down the list until information technology starts to veer into file names you don't recognize.
There are some cases where yous do intendance about the full stack, just they're few and far between, in my experience. Things similar… if y'all doubtable a bug in the library you're using, or if you retrieve some erroneous input is making its way into library code and blowing upwardly.
The vast majority of the fourth dimension, though, the bug volition be in your own code ;)
Follow the Clues: How to Diagnose the Error
Then the stack trace told usa where to expect: line ix of App.js. Allow's open that upwardly.
Here's the total text of that file:
import "./styles.css" ; export default function App () { allow items ; render ( < div className = "App" > < h1 > List of Items </ h1 > { items . map ( detail => ( < div fundamental = { item .id } > { item .name } </ div > )) } </ div > ) ; } Line 9 is this one:
And just for reference, here's that error message again:
TypeError: Cannot read property 'map' of undefined Permit's break this down!
-
TypeErroris the kind of fault
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 least useful part of the error bulletin)
-
Cannot read propertymeans the code was trying to read a holding.
This is a skillful clue! There are merely a few ways 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.
At that place's also brackets (aka square brackets, []) for accessing items in an array, like items[five] or items['map'].
You lot might wonder why the error isn't more specific, like "Cannot read role `map` of undefined" – but remember, the JS interpreter has no idea what we meant that blazon to exist. It doesn't know it was supposed to be an array, or that map is a role. It didn't get that far, because items is undefined.
-
'map'is the property the code was trying to read
This 1 is some other peachy clue. Combined with the previous bit, you can be 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 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 tin can slice this all together:
- notice the line that the error occurred on (line 9, here)
- scan that line looking for
.map - look at the variable/expression/any immediately earlier the
.mapand be very suspicious of it.
Once yous know which variable to expect at, you tin read through the function looking for where it comes from, and whether it's initialized.
In our petty instance, the simply other occurrence of items is line 4:
This defines the variable merely it doesn't set it to anything, which means its value is undefined. At that place's the problem. Fix that, and you lot set the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a simple mistake, and information technology's colocated very shut to the site of the fault. These ones are the easiest to set!
There are a ton of potential causes for an fault like this, though.
Perhaps items is a prop passed in from the parent component – and y'all forgot to pass information technology downward.
Or maybe you did pass that prop, only the value beingness passed in is really undefined or null.
If information technology's a local state variable, perchance you're initializing the land as undefined – useState(), written similar that with no arguments, will exercise exactly this!
If it'due south a prop coming from Redux, maybe your mapStateToProps is missing the value, or has a typo.
Whatever the case, though, the process is the same: showtime where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouthward or use the debugger to audit the intermediate values and figure out why it'due south undefined.
You'll go it fixed! 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-footstep approach, check out my Pure React workshop.
Larn to think in React
- 90+ screencast lessons
- Full transcripts and airtight captions
- All the code from the lessons
- Developer interviews
Start 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 devs wanting to upskill or consolidate.
berryhatioubjece1995.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "React Apollo Typeerror: Cannot Read Property '0' of Undefined"
Postar um comentário