Cannot Read Property 'documentelement' of Undefined Respond.js

Got an fault like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk nearly how to fix this one specifically, and along the manner yous'll learn how to arroyo fixing errors in general.

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

The Quick Fix

This fault commonly means y'all're trying to use .map on an array, but that assortment isn't defined all the same.

That's frequently because the array is a slice of undefined country or an undefined prop.

Make sure to initialize the land properly. That means if it will somewhen be an array, use useState([]) instead of something like useState() or useState(null).

Let's expect at how we can interpret an mistake message and rails downward where it happened and why.

How to Find the Error

First order of business is to effigy out where the error is.

If y'all're using Create React App, it probably threw upwards a screen like this:

TypeError

Cannot read holding 'map' of undefined

App

                                                                                                                          6 |                                                      render                                      (                                
seven | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div key = {item . id} >
11 | {particular . proper name}
12 | < / div >

Expect for the file and the line number first.

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

btw, when yous encounter something like /src/App.js:9:xiii, the manner to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If you lot're looking at the browser console instead, y'all'll demand to read the stack trace to effigy out where the mistake was.

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

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

Hither'south the stack trace for this error, with the merely important lines highlighted:

                                          TypeError: Cannot                                read                                  property                                '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.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $i                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.evolution.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.development.js:17672)                              at evaluate (alphabetize.js:7)                              at z (eval.js:42)                              at One thousand.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (director.js:257)                              at compile.ts:717                              at fifty (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              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 two lines are all nosotros care about here.

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

Allow'due south decode a couple of these lines:

Here we take:

  • 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 mistake occurred

Permit's look at some other 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 (information technology's a large 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 almost always ignore whatever lines that refer to files that are outside your codebase, like ones from a library.

Usually, that means y'all'll pay attention to just the first few lines.

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

There are some cases where you do intendance well-nigh the full stack, only 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 lot call back some erroneous input is making its way into library lawmaking and blowing up.

The vast majority of the time, though, the bug will be in your ain code ;)

Follow the Clues: How to Diagnose the Mistake

So the stack trace told united states where to look: line 9 of App.js. Allow'due south open that up.

Hither's the full text of that file:

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

Line 9 is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let'southward break this downwards!

  • TypeError is the kind of fault

At that place are a scattering of built-in mistake 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 function of the mistake message)

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

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

The most common is probably the . operator.

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

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

There'due south also 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 function `map` of undefined" – but remember, the JS interpreter has no idea what we meant that type to be. It doesn't know information technology was supposed to be 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 one is another great clue. Combined with the previous bit, you can be pretty certain you should be looking for .map somewhere on this line.

  • of undefined is a clue about the value of the variable

It would be fashion more useful if the mistake could say "Cannot read property `map` of items". Sadly it doesn't say that. Information technology tells y'all the value of that variable instead.

And then at present yous 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 expect at, y'all tin can read through the office looking for where it comes from, and whether information technology's initialized.

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

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

Fixing This in the Existent Globe

Of course this example is tiny and contrived, with a elementary mistake, and information technology'due south colocated very close to the site of the error. These ones are the easiest to set up!

There are a ton of potential causes for an error similar 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, simply the value being passed in is actually undefined or null.

If information technology'due south a local country variable, peradventure you're initializing the state equally undefined – useState(), written like that with no arguments, will do 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 process is the same: start where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouthward or use the debugger to inspect the intermediate values and figure out why information technology's undefined.

Y'all'll get it fixed! Adept luck :)

Success! At present check your email.

Learning React tin can be a struggle — and so many libraries and tools!
My advice? Ignore all of them :)
For a step-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 closed captions
  • All the code from the lessons
  • Programmer interviews

Start learning Pure React at present

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

Alan Lavender

Alan Lavender

@lavenderlens

vazquezlantoo.blogspot.com

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

0 Response to "Cannot Read Property 'documentelement' of Undefined Respond.js"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel