Uncaught Typeerror: Cannot Read Property 'object' of Undefined

Got an fault like this in your React component?

Cannot read property `map` of undefined

In this mail we'll talk near how to fix this 1 specifically, and along the way yous'll learn how to approach 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 information technology.

The Quick Ready

This mistake normally means yous're trying to use .map on an array, but that array isn't defined however.

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

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

Permit's look at how nosotros tin interpret an error message and track down where it happened and why.

How to Detect the Error

Offset guild of concern is to effigy out where the error is.

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

TypeError

Cannot read belongings 'map' of undefined

App

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

Expect for the file and the line number first.

Here, that's /src/App.js and line 9, taken from the lite gray text higher up the lawmaking cake.

btw, when you run across something like /src/App.js:9:13, the style 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 figure out where the error was.

These always 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 near recent starting time.

Hither's the stack trace for this error, with the merely 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.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.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.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.return (react-dom.evolution.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 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:three)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said yous could ignore near of it! The first ii lines are all nosotros care nigh hither.

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

Let's decode a couple of these lines:

Here we have:

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

Let'due south look at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper noun of the part where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it'due south 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 tin can virtually always ignore whatsoever lines that refer to files that are outside your codebase, similar ones from a library.

Normally, that means you'll pay attention to merely the offset few lines.

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

There are some cases where you do intendance about the total stack, just they're few and far between, in my experience. Things like… if you doubtable a bug in the library you lot're using, or if you recollect some erroneous input is making its manner into library code and bravado upwards.

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

Follow the Clues: How to Diagnose the Error

So the stack trace told u.s.a. where to look: line nine of App.js. Let's open that upwardly.

Hither's the full text of that file:

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

Line 9 is this one:

And simply for reference, here'south that error bulletin over again:

                          TypeError: Cannot read property 'map' of undefined                                    

Permit's intermission this downwards!

  • TypeError is the kind of mistake

There are a scattering of built-in mistake types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid type." (this part is, IMO, the least useful function of the error bulletin)

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

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

The most common is probably the . operator.

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

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

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

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

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

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

Then now you tin piece this all together:

  • notice the line that the error occurred on (line 9, hither)
  • scan that line looking for .map
  • look at the variable/expression/any immediately earlier the .map and be very suspicious of it.

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

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

This defines the variable simply it doesn't set it to annihilation, which means its value is undefined. There'southward the problem. Set that, and you fix the mistake!

Fixing This in the Real World

Of course this example is tiny and contrived, with a uncomplicated mistake, and it's colocated very close to the site of the fault. These ones are the easiest to fix!

In that location are a ton of potential causes for an error like this, though.

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

Or maybe y'all did laissez passer that prop, but the value being passed in is actually undefined or null.

If information technology's a local state variable, perhaps y'all're initializing the land as undefined – useState(), written like that with no arguments, will practise exactly this!

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

Whatever the case, though, the process is the aforementioned: offset 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 figure out why it's undefined.

You'll get it fixed! Practiced luck :)

Success! Now bank check your email.

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

Pure React plant

Learn to think in React

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

Start learning Pure React at present

Dave Ceddia'south 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 front end end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

townsancence.blogspot.com

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

0 Response to "Uncaught Typeerror: Cannot Read Property 'object' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel