Error Cannot Read Property 'name' of Undefined Lot Fallout 4

Got an error like this in your React component?

Cannot read holding `map` of undefined

In this post we'll talk about how to fix this one specifically, and forth the way 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 error, and ultimately how to prepare it.

The Quick Fix

This error usually means you're trying to employ .map on an array, just that array isn't defined yet.

That'southward ofttimes considering the array is a piece of undefined state or an undefined prop.

Make certain to initialize the state properly. That means if it will eventually exist an array, utilise useState([]) instead of something like useState() or useState(nix).

Permit'southward look at how we can interpret an mistake bulletin and track down where it happened and why.

How to Find the Error

Kickoff gild of business is to figure out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

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

Await 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 y'all see something similar /src/App.js:9:13, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If yous're looking at the browser console instead, y'all'll need to read the stack trace to figure out where the error was.

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

The lines are in gild of execution, with the well-nigh contempo first.

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

                                          TypeError: Cannot                                read                                  property                                'map'                                  of undefined                                                              at App (App.js:ix)                                            at renderWithHooks (react-dom.development.js:10021)                              at mountIndeterminateComponent (react-dom.development.js:12143)                              at beginWork (react-dom.evolution.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.evolution.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.development.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.evolution.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:vii)                              at z (eval.js:42)                              at One thousand.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (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.east.              <              computed              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:iii)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said y'all could ignore most of it! The first 2 lines are all we care virtually hither.

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

Permit'due south decode a couple of these lines:

Hither nosotros accept:

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

Let'southward look at another one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the name of the function 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 but I wanted to land information technology explictly: when you lot're looking at a stack trace, you lot can almost ever 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 but the first few lines.

Scan downwards the list until it starts to veer into file names y'all don't recognize.

There are some cases where you do care about the full stack, but they're few and far between, in my experience. Things like… if you suspect a bug in the library y'all're using, or if you think some erroneous input is making its way into library code and bravado up.

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

Follow the Clues: How to Diagnose the Error

So the stack trace told us where to look: line ix of App.js. Permit'south open up that up.

Here's the full text of that file:

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

Line ix is this one:

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

                          TypeError: Cannot read holding 'map' of undefined                                    

Let's interruption this down!

  • TypeError is the kind of fault

There are a handful of built-in fault 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 least useful part of the mistake message)

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

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

The most common is probably the . operator.

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

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

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

You 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 blazon to be. It doesn't know it was supposed to exist an array, 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 bang-up clue. Combined with the previous bit, you lot can be pretty sure you should be looking for .map somewhere on this line.

  • of undefined is a inkling most the value of the variable

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

And so now you tin piece this all together:

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

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

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

This defines the variable only it doesn't fix it to anything, which ways its value is undefined. There's the problem. Fix that, and y'all set the error!

Fixing This in the Real World

Of class this example is tiny and contrived, with a elementary fault, and it'south colocated very close to the site of the error. These ones are the easiest to prepare!

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

Maybe 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 being passed in is actually undefined or null.

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

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

Whatsoever the case, though, the procedure is the aforementioned: commencement 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's undefined.

You'll go it stock-still! Skilful luck :)

Success! Now check your email.

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

Pure React plant

Acquire to think in React

  • xc+ screencast lessons
  • Total transcripts and closed captions
  • All the lawmaking from the lessons
  • Developer interviews

Start learning Pure React now

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

Alan Lavender

Alan Lavender

@lavenderlens

wellstherhad.blogspot.com

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

0 Response to "Error Cannot Read Property 'name' of Undefined Lot Fallout 4"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel