React Redux Connect Mapstatetoprops Cannot Read Property

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk almost how to fix this one specifically, and along the way you'll acquire how to approach fixing errors in general.

We'll cover how to read a stack trace, how to translate the text of the fault, and ultimately how to fix it.

The Quick Fix

This mistake usually means you're trying to use .map on an array, but that array isn't defined yet.

That'southward often because the array is a piece of undefined country or an undefined prop.

Brand sure to initialize the state properly. That ways if information technology will eventually exist an assortment, use useState([]) instead of something like useState() or useState(zip).

Let's look at how nosotros can interpret an error bulletin and track down where it happened and why.

How to Find the Mistake

First social club of business is to figure out where the error is.

If yous're using Create React App, it probably threw upward a screen similar this:

TypeError

Cannot read holding 'map' of undefined

App

                                                                                                                          vi |                                                      render                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div key = {particular . id} >
11 | {detail . name}
12 | < / div >

Expect for the file and the line number kickoff.

Hither, that'due south /src/App.js and line 9, taken from the light greyness text in a higher place the lawmaking block.

btw, when y'all run across something like /src/App.js:9: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'll need to read the stack trace to figure out where the fault was.

These e'er wait long and intimidating, but the trick is that unremarkably you lot tin ignore almost of it!

The lines are in order of execution, with the most recent first.

Hither's the stack trace for this fault, 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.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.evolution.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.development.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.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 Yard.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (managing 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 adjacent] (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 commencement 2 lines are all nosotros care most here.

The first line is the error bulletin, and every line later on that spells out the unwound stack of office calls that led to it.

Let's decode a couple of these lines:

Here nosotros have:

  • App is the name of our component office
  • App.js is the file where it appears
  • nine is the line of that file where the fault occurred

Permit's look at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper noun of the function where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it'south a big file!)

Ignore Files That Aren't Yours

I already mentioned this just I wanted to state it explictly: when you're looking at a stack trace, yous can well-nigh always ignore any lines that refer to files that are outside your codebase, like ones from a library.

Usually, that ways you'll pay attention to only the first few lines.

Scan down the list until information technology starts to veer into file names yous don't recognize.

At that place are some cases where you exercise care nearly the full stack, just they're few and far between, in my feel. Things similar… if you suspect a problems in the library yous're using, or if y'all think some erroneous input is making its way into library lawmaking and bravado up.

The vast majority of the time, though, the issues will exist in your ain code ;)

Follow the Clues: How to Diagnose the Error

And then the stack trace told united states of america where to wait: line nine of App.js. Let'southward open that upwardly.

Here's the full text of that file:

                          import                                          "./styles.css"              ;              export                                          default                                          function                                          App              ()                                          {                                          let                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              particular                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .proper noun              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this i:

And just for reference, hither's that error message once again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's break this downward!

  • TypeError is the kind of error

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 to the lowest degree useful function of the error bulletin)

  • Cannot read property ways the code was trying to read a belongings.

This is a good clue! There are only a few means to read backdrop in JavaScript.

The most common is probably the . operator.

Every bit in user.proper name, to admission the name belongings of the user object.

Or items.map, to access the map property of the items object.

In that location's as well brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].

You might wonder why the error isn't more specific, similar "Cannot read function `map` of undefined" – but remember, the JS interpreter has no idea what nosotros meant that type to be. It doesn't know it was supposed to be an assortment, or that map is a function. It didn't get that far, because items is undefined.

  • 'map' is the property the code was trying to read

This one is another smashing inkling. Combined with the previous bit, you can be pretty sure y'all should be looking for .map somewhere on this line.

  • of undefined is a clue well-nigh the value of the variable

It would be mode more useful if the error could say "Cannot read property `map` of items". Sadly it doesn't say that. Information technology tells you the value of that variable instead.

So now you tin can piece this all together:

  • find the line that the fault occurred on (line 9, here)
  • browse that line looking for .map
  • look at the variable/expression/any immediately before the .map and be very suspicious of information technology.

Once you know which variable to wait at, you can read through the function looking for where information technology comes from, and whether it's initialized.

In our little case, the only other occurrence of items is line four:

This defines the variable but it doesn't prepare information technology to anything, which means its value is undefined. There's the problem. Fix that, and yous fix the error!

Fixing This in the Existent Globe

Of form 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 fix!

There are a ton of potential causes for an error like this, though.

Mayhap items is a prop passed in from the parent component – and you forgot to laissez passer information technology down.

Or maybe you did pass that prop, but the value being passed in is actually undefined or nada.

If it'due south a local state variable, peradventure 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, maybe your mapStateToProps is missing the value, or has a typo.

Whatever the case, though, the procedure 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.logs or use the debugger to inspect the intermediate values and effigy out why it'south undefined.

You'll get it fixed! Good luck :)

Success! Now bank check your email.

Learning React tin can be a struggle — and then many libraries and tools!
My advice? Ignore all of them :)
For a pace-by-pace approach, bank check out my Pure React workshop.

Pure React plant

Learn to call back in React

  • 90+ screencast lessons
  • Total transcripts and closed captions
  • All the code from the lessons
  • Developer interviews

Start learning Pure React at present

Dave Ceddia'due south Pure React is a piece of work of enormous clarity and depth. Hats off. I'one thousand a React trainer in London and would thoroughly recommend this to all forepart devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

cramerconalothe.blogspot.com

Source: https://daveceddia.com/fix-react-errors/

0 Response to "React Redux Connect Mapstatetoprops Cannot Read Property"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel