Redux Cannot Read Property Value of Undefined

Got an mistake like this in your React component?

Cannot read holding `map` of undefined

In this postal service we'll talk about how to fix this one specifically, and along the mode you'll learn how to arroyo fixing errors in general.

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

The Quick Set up

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

That's frequently because the array is a piece of undefined state or an undefined prop.

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

Permit'southward await at how we tin can interpret an fault message and track down where it happened and why.

How to Detect the Error

Showtime order of business is to effigy out where the mistake is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> nine | {items . map((item) => (
| ^
10 | < div central = {particular . 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 low-cal gray text above the code block.

btw, when you see something similar /src/App.js:9:13, the fashion to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If you're looking at the browser panel instead, yous'll need to read the stack trace to effigy out where the error was.

These always look long and intimidating, simply the trick is that usually you tin ignore nigh of it!

The lines are in order of execution, with the nigh recent get-go.

Here's the stack trace for this error, with the only of import 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              $i                              (react-dom.evolution.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.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 (alphabetize.js:seven)                              at z (eval.js:42)                              at G.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.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 nigh of it! The first 2 lines are all we care about hither.

The first line is the fault bulletin, and every line after that spells out the unwound stack of part calls that led to it.

Permit's decode a couple of these lines:

Hither we accept:

  • App is the name of our component role
  • App.js is the file where it appears
  • 9 is the line of that file where the error occurred

Let's look at another ane:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the proper 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 but I wanted to state it explictly: when you're looking at a stack trace, you can nearly e'er ignore any lines that refer to files that are outside your codebase, like ones from a library.

Commonly, that means yous'll pay attention to merely the first 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 exercise care virtually the full stack, but they're few and far betwixt, in my experience. Things like… if you doubtable a bug in the library you lot're using, or if you lot think some erroneous input is making its way into library code and bravado upwards.

The vast majority of the time, though, the bug will be in your own code ;)

Follow the Clues: How to Diagnose the Fault

So the stack trace told us where to look: line 9 of App.js. Let'due south open that upward.

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              (              item                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .proper name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this one:

And just for reference, hither'due south that fault message again:

                          TypeError: Cannot read property 'map' of undefined                                    

Permit's break this down!

  • TypeError is the kind of error

There are a scattering of congenital-in error 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 to the lowest degree useful role of the error message)

  • Cannot read belongings means the lawmaking was trying to read a holding.

This is a good clue! There are but a few ways to read properties in JavaScript.

The nearly common is probably the . operator.

As in user.proper noun, to admission the proper name property of the user object.

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

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

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

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

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

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

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

And so now you can piece this all together:

  • find the line that the error occurred on (line ix, hither)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately before the .map and be very suspicious of information technology.

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

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

This defines the variable just it doesn't set it to annihilation, which means its value is undefined. There's the problem. Fix that, and you prepare the error!

Fixing This in the Real World

Of form this example is tiny and contrived, with a unproblematic mistake, and information technology'due south colocated very close to the site of the fault. These ones are the easiest to set up!

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

Perchance items is a prop passed in from the parent component – and you forgot to pass information technology downwards.

Or maybe you did pass that prop, just the value beingness passed in is actually undefined or cypher.

If it's a local land variable, peradventure you're initializing the state as 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 case, though, the process 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.logs or use the debugger to inspect the intermediate values and effigy out why information technology's undefined.

Yous'll become information technology fixed! Good luck :)

Success! Now check your e-mail.

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

Pure React plant

Learn to recall in React

  • 90+ screencast lessons
  • Total transcripts and closed 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

mckinnonmices1984.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel