Uncaught (in Promise) Typeerror Cannot Read Property of Undefined React

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk about how to set this ane specifically, and along the way you'll learn how to approach fixing errors in general.

Nosotros'll embrace how to read a stack trace, how to interpret the text of the mistake, and ultimately how to fix it.

The Quick Gear up

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

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

Brand certain to initialize the state properly. That ways if it will eventually be an array, employ useState([]) instead of something like useState() or useState(null).

Allow's expect at how we can interpret an error message and rail down where it happened and why.

How to Observe the Error

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

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
viii | < h1 > Listing of Items < / h1 >
> nine | {items . map((item) => (
| ^
x | < div key = {detail . id} >
xi | {item . name}
12 | < / div >

Expect for the file and the line number beginning.

Here, that's /src/App.js and line 9, taken from the low-cal gray text above the code block.

btw, when you meet something like /src/App.js:9:thirteen, the fashion to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

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

The lines are in guild of execution, with the most recent beginning.

Hither's the stack trace for this mistake, with the merely important lines highlighted:

                                          TypeError: Cannot                                read                                  property                                'map'                                  of undefined                                                              at App (App.js:nine)                                            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.evolution.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.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.evolution.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.evolution.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at Thousand.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (managing director.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [as side by side] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said y'all could ignore most of information technology! The first 2 lines are all we intendance about here.

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

Let'south decode a couple of these lines:

Hither 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 wait at another one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the name of the part 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 you lot'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.

Usually, 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 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 you lot're using, or if you lot recollect some erroneous input is making its way into library code and blowing up.

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

Follow the Clues: How to Diagnose the Fault

So the stack trace told u.s. where to look: line ix of App.js. Let'due south open that up.

Here's the total text of that file:

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

Line 9 is this one:

And just for reference, here's that fault message once again:

                          TypeError: Cannot read holding 'map' of undefined                                    

Let's break this downward!

  • TypeError is the kind of error

There are a scattering of born 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 role of the error message)

  • Cannot read property means 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.

Every bit in user.proper name, to access the name holding of the user object.

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

There's too brackets (aka square brackets, []) for accessing items in an array, like items[five] or items['map'].

You might wonder why the error isn't more specific, like "Cannot read part `map` of undefined" – merely call back, the JS interpreter has no thought what we meant that type to be. It doesn't know it was supposed to be an assortment, 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 lot tin can be pretty sure you should be looking for .map somewhere on this line.

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

It would exist way 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.

And so now you tin can piece this all together:

  • find the line that the error occurred on (line ix, 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 yous know which variable to look at, y'all can read through the part looking for where information technology comes from, and whether information technology's initialized.

In our little example, the simply other occurrence of items is line four:

This defines the variable but it doesn't set it to anything, which ways its value is undefined. There'southward the trouble. Fix that, and you fix the error!

Fixing This in the Real World

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

At that place are a ton of potential causes for an error similar this, though.

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

Or maybe y'all did pass that prop, simply the value beingness passed in is actually undefined or null.

If it's a local state variable, maybe you lot're initializing the state every bit undefined – useState(), written like that with no arguments, will practice exactly this!

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

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

Yous'll get it fixed! Good luck :)

Success! At present check your email.

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

Pure React plant

Learn to think in React

  • xc+ screencast lessons
  • Full transcripts and closed captions
  • All the code from the lessons
  • Developer interviews

Starting time learning Pure React now

Dave Ceddia's Pure React is a piece of 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

marshallunswed.blogspot.com

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

0 Response to "Uncaught (in Promise) Typeerror Cannot Read Property of Undefined React"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel