Redux Typeerror: Cannot Read Property 'store' of Undefined
Got an fault like this in your React component?
Cannot read belongings `map` of undefined
In this post nosotros'll talk about how to fix this one specifically, and along the way you'll learn how to approach fixing errors in general.
We'll cover how to read a stack trace, how to interpret the text of the fault, and ultimately how to ready it.
The Quick Set up
This error normally ways you're trying to utilize .map
on an array, only that array isn't defined however.
That'south often because the array is a piece of undefined state or an undefined prop.
Make sure to initialize the state properly. That ways if it will eventually be an array, utilize useState([])
instead of something like useState()
or useState(null)
.
Allow'southward look at how nosotros tin can interpret an fault message and track down where information technology happened and why.
How to Find the Error
First order of business is to figure out where the mistake is.
If you're using Create React App, it probably threw up a screen like this:
TypeError
Cannot read holding 'map' of undefined
App
half-dozen | return (
7 | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> nine | {items . map((item) => (
| ^
10 | < div key = {item . id} >
11 | {item . proper name}
12 | < / div >
Look for the file and the line number first.
Here, that's /src/App.js and line 9, taken from the light greyness text in a higher place the code block.
btw, when you see something like /src/App.js:ix:xiii
, the fashion to decode that is filename:lineNumber:columnNumber.
How to Read the Stack Trace
If you're looking at the browser console instead, you'll need to read the stack trace to figure out where the mistake was.
These ever look long and intimidating, only the play tricks is that usually you can ignore most of it!
The lines are in guild of execution, with the most recent showtime.
Hither'southward the stack trace for this error, with the but important lines highlighted:
TypeError: Cannot read belongings 'map' of undefined at App (App.js:9) at renderWithHooks (react-dom.evolution.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.development.js:15339) at workLoopSync (react-dom.evolution.js:15293) at renderRootSync (react-dom.evolution.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.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 be.evaluateTranspiledModule (director.js:286) at be.evaluateModule (manager.js:257) at compile.ts:717 at fifty (runtime.js:45) at Generator._invoke (runtime.js:274) at Generator.forEach.due east. < 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 information technology! The first 2 lines are all nosotros intendance about hither.
The first line is the error bulletin, and every line after that spells out the unwound stack of function calls that led to it.
Let's decode a couple of these lines:
Here we accept:
-
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 fault occurred
Let'south look at another 1:
at performSyncWorkOnRoot (react-dom.development.js:15008)
-
performSyncWorkOnRoot
is the name of the function where this happened -
react-dom.development.js
is the file -
15008
is the line number (it's a big file!)
Ignore Files That Aren't Yours
I already mentioned this simply I wanted to state it explictly: when you're looking at a stack trace, you can almost always ignore any lines that refer to files that are outside your codebase, similar ones from a library.
Usually, that means you'll pay attention to but the kickoff few lines.
Scan down the list until information technology starts to veer into file names you don't recognize.
In that location are some cases where you do care most the full stack, but they're few and far between, in my experience. Things like… if you suspect a issues in the library you're using, or if you think some erroneous input is making its fashion into library code and blowing up.
The vast majority of the time, though, the bug will exist in your own code ;)
Follow the Clues: How to Diagnose the Mistake
So the stack trace told us where to look: line nine of App.js. Let'due south open that up.
Here's the full text of that file:
import "./styles.css" ; export default function App () { let items ; render ( < div className = "App" > < h1 > Listing of Items </ h1 > { items . map ( item => ( < div key = { item .id } > { particular .proper name } </ div > )) } </ div > ) ; }
Line ix is this ane:
And but for reference, hither's that error message again:
TypeError: Cannot read holding 'map' of undefined
Let's pause this down!
-
TypeError
is the kind of error
In that location are a handful of congenital-in error types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is non of a valid type." (this part is, IMO, the least useful part of the error bulletin)
-
Cannot read property
means the code was trying to read a property.
This is a good clue! There are but a few ways to read properties in JavaScript.
The most common is probably the .
operator.
As in user.name
, to access the name
belongings of the user
object.
Or items.map
, to access the map
property of the items
object.
There's as well brackets (aka square brackets, []
) for accessing items in an array, like items[v]
or items['map']
.
You might wonder why the error isn't more specific, similar "Cannot read function `map` of undefined" – simply remember, the JS interpreter has no idea what we meant that type to be. It doesn't know it was supposed to be an array, or that map
is a role. It didn't go that far, because items
is undefined.
-
'map'
is the property the code was trying to read
This i is another great clue. Combined with the previous bit, you lot tin be pretty sure you should be looking for .map
somewhere on this line.
-
of undefined
is a clue about the value of the variable
It would exist way more useful if the error could say "Cannot read belongings `map` of items". Sadly it doesn't say that. Information technology tells you the value of that variable instead.
So now you can piece this all together:
- detect the line that the error occurred on (line 9, here)
- scan that line looking for
.map
- look at the variable/expression/whatsoever immediately before the
.map
and exist very suspicious of information technology.
In one case yous know which variable to look at, y'all can read through the role looking for where it comes from, and whether it'south initialized.
In our little example, the only other occurrence of items
is line 4:
This defines the variable but it doesn't prepare it to anything, which means its value is undefined
. There'southward the problem. Fix that, and you fix the fault!
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 like this, though.
Maybe items
is a prop passed in from the parent component – and y'all forgot to pass it downwardly.
Or maybe y'all did pass that prop, merely the value being passed in is actually undefined or zippo.
If it'southward a local state variable, maybe you lot're initializing the country as undefined – useState()
, written similar that with no arguments, will practice exactly this!
If information technology's a prop coming from Redux, maybe your mapStateToProps
is missing the value, or has a typo.
Whatever the example, though, the process is the same: start where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
s or employ the debugger to inspect the intermediate values and effigy out why it'due south undefined.
Yous'll get it stock-still! Good luck :)
Success! Now cheque your email.
Learning React can exist a struggle — so many libraries and tools!
My communication? Ignore all of them :)
For a step-by-step approach, cheque out my Pure React workshop.
Learn to think in React
- 90+ screencast lessons
- Full transcripts and airtight captions
- All the lawmaking from the lessons
- Developer interviews
Starting time learning Pure React now
Dave Ceddia'south Pure React is a piece of work of enormous clarity and depth. Hats off. I'grand a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.
fountainmighter42.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Redux Typeerror: Cannot Read Property 'store' of Undefined"
Post a Comment