Redux Typeerror: Cannot Read Property 'value' of Undefined

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this post we'll talk most how to fix this one specifically, and along the way you'll learn how to arroyo fixing errors in general.

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

The Quick Fix

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

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

Brand sure to initialize the state properly. That ways if it will eventually be an array, use useState([]) instead of something like useState() or useState(nil).

Let's look at how we can interpret an fault message and track downwardly where information technology happened and why.

How to Find the Error

First order of business concern is to figure out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > Listing of Items < / h1 >
> ix | {items . map((item) => (
| ^
ten | < div central = {item . id} >
xi | {item . name}
12 | < / div >

Look for the file and the line number first.

Here, that's /src/App.js and line 9, taken from the calorie-free gray text above the code block.

btw, when you 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 lot'll need to read the stack trace to figure out where the mistake was.

These always look long and intimidating, but the trick is that unremarkably yous can ignore virtually of information technology!

The lines are in order of execution, with the well-nigh recent start.

Here's the stack trace for this error, with the only of import lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                '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.evolution.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.development.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.evolution.js:15268)                              at performSyncWorkOnRoot (react-dom.evolution.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.development.js:17609)                              at Object.render (react-dom.evolution.js:17672)                              at evaluate (alphabetize.js:7)                              at z (eval.js:42)                              at M.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at exist.evaluateModule (director.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.east.              <              computed              >                              [every bit next] (runtime.js:97)                              at t (asyncToGenerator.js:three)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore most of it! The first 2 lines are all we intendance about hither.

The outset line is the error message, and every line later on that spells out the unwound stack of function calls that led to information technology.

Permit'south decode a couple of these lines:

Hither nosotros have:

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

Let's wait at another 1:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the name of the role where this happened
  • react-dom.evolution.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 y'all're looking at a stack trace, you lot can almost always ignore whatsoever lines that refer to files that are exterior your codebase, like ones from a library.

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

Scan downwardly the list until it starts to veer into file names you lot don't recognize.

There are some cases where you do care about the full stack, merely they're few and far between, in my experience. Things like… if you suspect a problems in the library you're using, or if y'all call back some erroneous input is making its manner into library lawmaking and blowing up.

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 ix of App.js. Let's open that upwardly.

Here's the total text of that file:

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

Line nine is this one:

And only for reference, here's that fault bulletin again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'due south break this down!

  • TypeError is the kind of error

In that location are a scattering 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 function is, IMO, the least useful part of the error message)

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

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

The most common is probably the . operator.

Every bit 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 also 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" – but remember, the JS interpreter has no idea what we meant that type to exist. It doesn't know it was supposed to exist an assortment, or that map is a function. It didn't become that far, because items is undefined.

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

This 1 is another great clue. Combined with the previous fleck, you 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 be manner more than useful if the error 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 at present you can slice this all together:

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

In one case you know which variable to look at, you tin read through the part looking for where information technology comes from, and whether information technology'due south initialized.

In our footling example, the simply other occurrence of items is line 4:

This defines the variable merely it doesn't set up it to anything, which means its value is undefined. There's the problem. Fix that, and you fix the error!

Fixing This in the Existent World

Of course this example is tiny and contrived, with a elementary error, and it'south 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 similar this, though.

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

Or maybe you did laissez passer that prop, but the value existence passed in is actually undefined or null.

If it's a local state variable, maybe you're initializing the country every bit undefined – useState(), written similar that with no arguments, will exercise 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: first where the error is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and figure out why it'south undefined.

You'll get it stock-still! Good luck :)

Success! Now cheque your electronic mail.

Learning React tin exist a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a pace-by-step approach, cheque out my Pure React workshop.

Pure React plant

Acquire to recall in React

  • 90+ screencast lessons
  • Full transcripts and closed captions
  • All the lawmaking from the lessons
  • Programmer interviews

First learning Pure React at present

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

Alan Lavender

Alan Lavander

@lavenderlens

huntapse1965.blogspot.com

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

0 Response to "Redux Typeerror: Cannot Read Property 'value' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel