Uncaught Typeerror: Cannot Read Property 'location' of Null
Got an error like this in your React component?
Cannot read property `map` of undefined
In this post we'll talk about how to prepare this i specifically, and along the way you'll learn how to approach fixing errors in general.
Nosotros'll encompass how to read a stack trace, how to interpret the text of the mistake, and ultimately how to set up information technology.
The Quick Fix
This error usually ways you're trying to use .map
on an array, but that array isn't defined yet.
That'due south often considering the assortment is a piece of undefined state or an undefined prop.
Make certain to initialize the state properly. That ways if it will eventually be an array, use useState([])
instead of something like useState()
or useState(zip)
.
Let's wait at how we can interpret an mistake message and rail down where it happened and why.
How to Find the Error
First order of business organization is to figure out where the error is.
If y'all're using Create React App, information technology probably threw upwardly a screen like this:
TypeError
Cannot read property 'map' of undefined
App
half-dozen | return (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> ix | {items . map((particular) => (
| ^
10 | < div key = {particular . id} >
11 | {item . proper noun}
12 | < / div >
Await for the file and the line number starting time.
Here, that'due south /src/App.js and line 9, taken from the lite gray text above the lawmaking cake.
btw, when yous run across something similar /src/App.js:ix:xiii
, the mode to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If yous're looking at the browser panel instead, you'll need to read the stack trace to effigy out where the error was.
These ever look long and intimidating, but the flim-flam is that usually you can ignore most of it!
The lines are in order of execution, with the most recent kickoff.
Hither'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.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 $1 (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.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.return (react-dom.development.js:17672) at evaluate (index.js:seven) at z (eval.js:42) at K.evaluate (transpiled-module.js:692) at be.evaluateTranspiledModule (manager.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.east. < computed > [as side by side] (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 information technology! The kickoff 2 lines are all we care about here.
The kickoff line is the fault message, and every line later on that spells out the unwound stack of function calls that led to it.
Let's decode a couple of these lines:
Here nosotros have:
-
App
is the name of our component function -
App.js
is the file where it appears -
9
is the line of that file where the error occurred
Let's expect at some other one:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the role where this happened -
react-dom.development.js
is the file -
15008
is the line number (information technology's a big 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 almost e'er ignore whatever lines that refer to files that are outside your codebase, like ones from a library.
Usually, that means you'll pay attention to only the commencement few lines.
Scan down the list until it starts to veer into file names you don't recognize.
In that location are some cases where yous do care about the total stack, but they're few and far betwixt, in my experience. Things like… if you lot suspect a bug in the library you're using, or if you call up some erroneous input is making its way into library code and blowing upward.
The vast bulk of the time, though, the bug will be in your own code ;)
Follow the Clues: How to Diagnose the Fault
Then the stack trace told us where to expect: line nine of App.js. Let'southward open that up.
Here'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 = { item .id } > { item .name } </ div > )) } </ div > ) ; }
Line nine is this one:
And just for reference, here'due south that error message again:
TypeError: Cannot read belongings 'map' of undefined
Permit'south interruption this downwards!
-
TypeError
is the kind of mistake
There are a scattering of built-in fault types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful office of the mistake bulletin)
-
Cannot read property
means the code was trying to read a property.
This is a expert inkling! At that place are simply a few ways to read properties in JavaScript.
The well-nigh mutual is probably the .
operator.
Equally in user.name
, to access the proper name
property of the user
object.
Or items.map
, to access the map
property of the items
object.
There's likewise brackets (aka foursquare brackets, []
) for accessing items in an assortment, like items[5]
or items['map']
.
You might wonder why the mistake isn't more than specific, like "Cannot read part `map` of undefined" – only remember, the JS interpreter has no thought what nosotros meant that blazon to exist. Information technology doesn't know it was supposed to be an array, or that map
is a part. It didn't go that far, because items
is undefined.
-
'map'
is the holding the code was trying to read
This one is another keen clue. Combined with the previous bit, you can be pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue almost the value of the variable
It would exist mode more than useful if the fault could say "Cannot read property `map` of items". Sadly it doesn't say that. It tells y'all the value of that variable instead.
So now yous tin can piece 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/any immediately before the
.map
and be very suspicious of it.
Once you know which variable to look at, you tin can read through the function looking for where it comes from, and whether it'southward initialized.
In our picayune example, the only other occurrence of items
is line four:
This defines the variable but it doesn't set it to annihilation, which means its value is undefined
. There'due south the trouble. 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 close to the site of the error. These ones are the easiest to gear up!
There are a ton of potential causes for an error similar this, though.
Maybe items
is a prop passed in from the parent component – and yous forgot to laissez passer it down.
Or perhaps yous did pass that prop, but the value being passed in is actually undefined or null.
If it's a local state variable, maybe you're initializing the land equally undefined – useState()
, written similar that with no arguments, will do exactly this!
If it's a prop coming from Redux, maybe your mapStateToProps
is missing the value, or has a typo.
Any the example, though, the procedure is the same: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
s or use the debugger to inspect the intermediate values and figure out why it's undefined.
You'll go it stock-still! Skilful luck :)
Success! Now check your email.
Learning React can be a struggle — so many libraries and tools!
My communication? Ignore all of them :)
For a pace-by-step approach, check out my Pure React workshop.
Acquire to call back in React
- 90+ screencast lessons
- Full transcripts and closed captions
- All the code from the lessons
- Developer interviews
Kickoff learning Pure React at present
Dave Ceddia'due south Pure React is a piece of work of enormous clarity and depth. Hats off. I'1000 a React trainer in London and would thoroughly recommend this to all front stop devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Uncaught Typeerror: Cannot Read Property 'location' of Null"
ارسال یک نظر