Uncaught Typeerror: Cannot Read Property 'direction' of Undefined

Got an mistake like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to gear up this one specifically, and forth the manner you'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 it.

The Quick Ready

This error ordinarily means you lot're trying to utilize .map on an assortment, but that array isn't defined yet.

That's often because the array is a piece of undefined state or an undefined prop.

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

Let'south wait at how we can interpret an mistake bulletin and track down where it happened and why.

How to Discover the Error

First gild of concern is to figure out where the error is.

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

TypeError

Cannot read holding 'map' of undefined

App

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

Wait for the file and the line number showtime.

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

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

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

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

Here'southward the stack trace for this error, 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.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.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.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 (index.js:7)                              at z (eval.js:42)                              at Grand.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.e.              <              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 well-nigh of it! The outset 2 lines are all nosotros intendance most here.

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

Permit's decode a couple of these lines:

Here we have:

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

Let's look at another 1:

                          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 big file!)

Ignore Files That Aren't Yours

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

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

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

At that place 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 problems in the library yous're using, or if you lot think some erroneous input is making its mode into library lawmaking and bravado up.

The vast majority of the fourth dimension, though, the issues will be in your own lawmaking ;)

Follow the Clues: How to Diagnose the Error

So the stack trace told united states of america where to expect: line nine of App.js. Allow's open that up.

Here'southward the full text of that file:

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

Line 9 is this one:

And simply for reference, hither'southward that error bulletin once more:

                          TypeError: Cannot read belongings 'map' of undefined                                    

Let's pause this down!

  • TypeError is the kind of error

There are a handful of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this role is, IMO, the to the lowest degree useful office of the fault message)

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

This is a skillful clue! In that location are only a few ways to read properties in JavaScript.

The most common is probably the . operator.

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

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

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

Yous might wonder why the fault 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. Information technology doesn't know it was supposed to exist an array, or that map is a function. It didn't get that far, considering items is undefined.

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

This one is another neat 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 about the value of the variable

It would be style more 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.

So at present you can piece this all together:

  • find the line that the error occurred on (line nine, hither)
  • browse 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 can read through the function looking for where information technology comes from, and whether it'south initialized.

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

This defines the variable but it doesn't set it to anything, which ways its value is undefined. At that place's the problem. Gear up that, and you fix the mistake!

Fixing This in the Existent World

Of class this example is tiny and contrived, with a simple mistake, and it's colocated very shut to the site of the mistake. These ones are the easiest to fix!

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

Maybe items is a prop passed in from the parent component – and y'all forgot to pass it down.

Or maybe you did pass that prop, simply the value being passed in is actually undefined or zippo.

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

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

Whatsoever the case, though, the process is the same: start where the error is and piece of work backwards, verifying your assumptions at each signal the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and figure out why it'southward undefined.

Y'all'll go it fixed! Skilful luck :)

Success! Now check your email.

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

Pure React plant

Learn to call up in React

  • 90+ screencast lessons
  • Total transcripts and closed captions
  • All the code from the lessons
  • Developer interviews

Kickoff learning Pure React at present

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

Alan Lavender

Alan Lavender

@lavenderlens

ricecamraithe.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel