Unknown Error: Message: Typeerror: Cannot Read Property 'name' of Undefined

Got an error similar this in your React component?

Cannot read property `map` of undefined

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

Nosotros'll embrace how to read a stack trace, how to translate the text of the error, and ultimately how to gear up it.

The Quick Ready

This mistake commonly means yous're trying to use .map on an array, simply that assortment isn't defined yet.

That'due south oft considering the array is a slice of undefined state or an undefined prop.

Make sure to initialize the state properly. That means if information technology will eventually be an assortment, apply useState([]) instead of something similar useState() or useState(null).

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

How to Discover the Error

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

If yous're using Create React App, information technology probably threw up a screen like this:

TypeError

Cannot read belongings 'map' of undefined

App

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

Look for the file and the line number get-go.

Here, that's /src/App.js and line 9, taken from the light gray text above the lawmaking block.

btw, when you come across something like /src/App.js:9:thirteen, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

These e'er look long and intimidating, but the trick is that usually you can ignore most of it!

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

Here'due south the stack trace for this error, with the simply important lines highlighted:

                                          TypeError: Cannot                                read                                  belongings                                'map'                                  of undefined                                                              at App (App.js:nine)                                            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.evolution.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.evolution.js:2770)                              at invokeGuardedCallback (react-dom.evolution.js:2804)                              at beginWork              $1                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.evolution.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.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.development.js:17672)                              at evaluate (index.js:seven)                              at z (eval.js:42)                              at Yard.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (managing director.js:257)                              at compile.ts:717                              at 50 (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [equally next] (runtime.js:97)                              at t (asyncToGenerator.js:three)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore near of it! The first 2 lines are all we care about here.

The first line is the mistake message, and every line after that spells out the unwound stack of function calls that led to information technology.

Permit'south decode a couple of these lines:

Here we take:

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

Let's wait at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the role 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 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, similar ones from a library.

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

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

At that place are some cases where yous do care well-nigh the total stack, but they're few and far between, in my feel. Things similar… if yous suspect a problems in the library you're using, or if you think some erroneous input is making its way into library code and blowing up.

The vast majority of the time, though, the issues volition be in your own code ;)

Follow the Clues: How to Diagnose the Fault

So the stack trace told u.s.a. where to wait: line 9 of App.js. Let'due south open up that up.

Here'due south the total text of that file:

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

Line 9 is this i:

And just for reference, here's that mistake message again:

                          TypeError: Cannot read belongings 'map' of undefined                                    

Permit'south break this downward!

  • TypeError is the kind of error

At that place are a handful of born error types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is not of a valid blazon." (this part is, IMO, the least useful part of the fault message)

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

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

The near common is probably the . operator.

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

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

There's also brackets (aka square brackets, []) for accessing items in an array, similar items[v] or items['map'].

You might wonder why the error isn't more specific, like "Cannot read role `map` of undefined" – but remember, the JS interpreter has no thought what we meant that blazon to be. Information technology doesn't know it was supposed to be an array, or that map is a function. Information technology didn't get that far, because items is undefined.

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

This one is another great clue. Combined with the previous bit, you can 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 way more than useful if the error could say "Cannot read belongings `map` of items". Sadly it doesn't say that. It tells yous the value of that variable instead.

And so now yous tin piece this all together:

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

In one case you know which variable to look at, y'all can read through the office looking for where it comes from, and whether it's initialized.

In our little example, the just other occurrence of items is line iv:

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

Fixing This in the Real World

Of form this case is tiny and contrived, with a elementary error, and it's colocated very close to the site of the fault. These ones are the easiest to gear up!

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

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

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

If it's a local land variable, maybe y'all'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, perchance your mapStateToProps is missing the value, or has a typo.

Any the case, though, the process is the same: kickoff where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouth or utilize the debugger to audit the intermediate values and figure out why it's undefined.

You lot'll get it fixed! Good 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-past-step approach, check out my Pure React workshop.

Pure React plant

Learn to retrieve in React

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

Offset learning Pure React now

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

Alan Lavender

Alan Lavander

@lavenderlens

Unknown Error: Message: Typeerror: Cannot Read Property 'name' of Undefined

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

0 Response to "Unknown Error: Message: Typeerror: Cannot Read Property 'name' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel