Uncaught Typeerror: Cannot Read Property 'ownerdocument' of Undefined

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this mail service nosotros'll talk most how to fix this one specifically, and along the style you'll learn how to approach fixing errors in full general.

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

The Quick Prepare

This fault usually means y'all're trying to employ .map on an assortment, but that array isn't defined yet.

That's often considering the assortment is a piece of undefined state or an undefined prop.

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

Allow's look at how we tin can interpret an error bulletin and track downwards where it happened and why.

How to Find the Fault

First social club of concern is to figure out where the fault is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      render                                      (                                
vii | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div cardinal = {item . id} >
xi | {item . name}
12 | < / div >

Look for the file and the line number showtime.

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

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

These always expect long and intimidating, just the trick is that usually you tin can ignore most of it!

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

Here's the stack trace for this mistake, with the only 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.evolution.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.evolution.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.evolution.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.evolution.js:17672)                              at evaluate (alphabetize.js:vii)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at exist.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.due east.              <              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 most of information technology! The first 2 lines are all we care about hither.

The showtime line is the error bulletin, and every line after that spells out the unwound stack of office calls that led to information technology.

Let's decode a couple of these lines:

Here we have:

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

Let'south look at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the function where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it'southward a large file!)

Ignore Files That Aren't Yours

I already mentioned this only I wanted to state it explictly: when you're looking at a stack trace, y'all can almost always ignore any lines that refer to files that are exterior your codebase, like ones from a library.

Usually, that ways you lot'll pay attention to simply the first few lines.

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

There are some cases where yous do care about the full stack, simply they're few and far between, in my experience. Things similar… if you doubtable a problems in the library you lot're using, or if you think some erroneous input is making its manner into library code and bravado upwards.

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

Follow the Clues: How to Diagnose the Mistake

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

Here's the total text of that file:

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

Line 9 is this 1:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Allow'south break this down!

  • TypeError is the kind of error

In that location 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 least useful office of the fault message)

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

This is a good inkling! There are merely a few means 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 access the map holding of the items object.

There's besides brackets (aka foursquare brackets, []) for accessing items in an array, like items[5] 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 idea what we 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 get that far, because items is undefined.

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

This one is another bully clue. Combined with the previous bit, you tin be pretty sure you should be looking for .map somewhere on this line.

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

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

So now you lot can piece this all together:

  • find the line that the error occurred on (line 9, here)
  • 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 look at, you tin read through the office looking for where information technology comes from, and whether information technology's initialized.

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

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

Fixing This in the Real World

Of course this instance is tiny and contrived, with a elementary fault, and information technology's colocated very close to the site of the error. These ones are the easiest to prepare!

At that place are a ton of potential causes for an mistake like this, though.

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

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

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

If it'due south a prop coming from Redux, maybe your mapStateToProps is missing the value, or has a typo.

Whatever the case, though, the process is the aforementioned: outset where the fault 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 it'due south undefined.

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

Success! Now check your email.

Learning React can be a struggle — and so many libraries and tools!
My communication? Ignore all of them :)
For a footstep-by-step approach, bank check out my Pure React workshop.

Pure React plant

Learn to call up 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'southward 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 devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

gresswelljustong.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel