Redux Cannot Read Property of Undefined State

Got an fault like this in your React component?

Cannot read holding `map` of undefined

In this post nosotros'll talk well-nigh how to fix this one specifically, and forth the fashion you'll learn 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 error usually means you lot're trying to use .map on an array, only that array isn't defined yet.

That's often because the array is a slice of undefined country or an undefined prop.

Make sure to initialize the land properly. That means if it will somewhen be an array, use useState([]) instead of something similar useState() or useState(null).

Permit's expect at how nosotros can translate an mistake message and track downwards where it happened and why.

How to Discover the Error

First club of business concern is to figure out where the mistake is.

If y'all're using Create React App, it probably threw up a screen similar this:

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          6 |                                                      render                                      (                                
7 | < div className = "App" >
viii | < h1 > Listing of Items < / h1 >
> nine | {items . map((detail) => (
| ^
10 | < div key = {item . id} >
11 | {item . name}
12 | < / div >

Look for the file and the line number beginning.

Here, that'southward /src/App.js and line 9, taken from the light gray text above the code cake.

btw, when you see something similar /src/App.js:nine:xiii, 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 effigy out where the error was.

These always expect long and intimidating, but the trick is that ordinarily you can ignore almost of it!

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

Here's the stack trace for this mistake, 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.evolution.js:2804)                              at beginWork              $i                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.evolution.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.development.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.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 exist.evaluateModule (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [every bit 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 it! The first 2 lines are all nosotros care about here.

The commencement line is the fault message, and every line after that spells out the unwound stack of function calls that led to it.

Allow's decode a couple of these lines:

Here nosotros accept:

  • App is the name of our component function
  • App.js is the file where information technology appears
  • 9 is the line of that file where the mistake occurred

Let'south look at another i:

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

Ignore Files That Aren't Yours

I already mentioned this but I wanted to state information technology 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, like ones from a library.

Usually, that means you'll pay attention to merely the starting time 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 y'all do care about the total stack, but they're few and far between, in my experience. Things like… if you suspect a bug in the library you're using, or if you call up some erroneous input is making its manner into library code and bravado up.

The vast bulk of the time, though, the bug volition be in your ain code ;)

Follow the Clues: How to Diagnose the Error

Then the stack trace told the states where to look: line 9 of App.js. Allow's open that upward.

Here's the full text of that file:

                          import                                          "./styles.css"              ;              export                                          default                                          function                                          App              ()                                          {                                          allow                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              Listing of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          fundamental              =              {              item              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this 1:

And only for reference, here's that error message once again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'southward break this downwards!

  • TypeError is the kind of error

In that location 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 part of the mistake bulletin)

  • Cannot read holding means the code was trying to read a property.

This is a good inkling! There are simply a few ways to read properties in JavaScript.

The almost common is probably the . operator.

Equally in user.name, to access the name holding of the user object.

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

At that place'due south also brackets (aka square brackets, []) for accessing items in an array, similar items[5] or items['map'].

Yous might wonder why the error isn't more specific, like "Cannot read function `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 assortment, or that map is a office. 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 clue. Combined with the previous fleck, you can exist pretty sure you should be looking for .map somewhere on this line.

  • of undefined is a clue near the value of the variable

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

Then now you tin can piece this all together:

  • notice the line that the error occurred on (line 9, here)
  • browse that line looking for .map
  • look at the variable/expression/whatever immediately before the .map and be very suspicious of it.

In one case you know which variable to await at, you can read through the function looking for where it comes from, and whether it'due south initialized.

In our little example, the merely other occurrence of items is line 4:

This defines the variable but it doesn't fix information technology to anything, which means its value is undefined. At that place's the trouble. Fix that, and you fix the error!

Fixing This in the Real World

Of form this example is tiny and contrived, with a simple fault, and information technology's colocated very close to the site of the error. These ones are the easiest to ready!

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

Peradventure items is a prop passed in from the parent component – and you forgot to pass it down.

Or mayhap you did pass that prop, but the value being passed in is really undefined or null.

If it's a local state variable, maybe you're initializing the state as undefined – useState(), written like that with no arguments, will do exactly this!

If information technology's a prop coming from Redux, mayhap your mapStateToProps is missing the value, or has a typo.

Any the example, though, the process is the same: first where the error is and work backwards, verifying your assumptions at each bespeak the variable is used. Throw in some panel.logsouth or use the debugger to inspect the intermediate values and figure out why it's undefined.

You lot'll get it fixed! Skillful luck :)

Success! Now bank check your email.

Learning React can be a struggle — and so many libraries and tools!
My advice? Ignore all of them :)
For a footstep-by-step arroyo, check out my Pure React workshop.

Pure React plant

Learn to think in React

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

Start 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.

Alan Lavender

Alan Lavender

@lavenderlens

carmichaelforwas.blogspot.com

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

0 Response to "Redux Cannot Read Property of Undefined State"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel