Uncaught (in Promise) Typeerror: Cannot Read Property 'map' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk nigh how to set up this one specifically, and forth the fashion 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 fault, and ultimately how to fix it.

The Quick Fix

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

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

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

Permit'due south look at how we can interpret an error message and track down where it happened and why.

How to Find the Error

Commencement order of business is to figure out where the error 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 |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div key = {item . id} >
xi | {item . proper noun}
12 | < / div >

Await 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 code block.

btw, when y'all see something like /src/App.js:9:thirteen, 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 fox is that unremarkably you lot can ignore near of information technology!

The lines are in order of execution, with the near recent get-go.

Hither'southward the stack trace for this error, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  belongings                                'map'                                  of undefined                                                              at App (App.js:9)                                            at renderWithHooks (react-dom.evolution.js:10021)                              at mountIndeterminateComponent (react-dom.evolution.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.development.js:2804)                              at beginWork              $one                              (react-dom.evolution.js:16114)                              at performUnitOfWork (react-dom.development.js:15339)                              at workLoopSync (react-dom.evolution.js:15293)                              at renderRootSync (react-dom.development.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.evolution.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.evolution.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:vii)                              at z (eval.js:42)                              at Chiliad.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (director.js:286)                              at be.evaluateModule (manager.js:257)                              at compile.ts:717                              at fifty (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [as adjacent] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you lot could ignore well-nigh of it! The starting time 2 lines are all nosotros care about hither.

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

Allow's decode a couple of these lines:

Here we take:

  • 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

Allow's expect at some other i:

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

Ignore Files That Aren't Yours

I already mentioned this just I wanted to state it explictly: when y'all're looking at a stack trace, you can virtually always ignore whatever 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 it starts to veer into file names you don't recognize.

There are some cases where you exercise care nearly the full stack, merely they're few and far between, in my experience. Things similar… if you suspect a bug in the library you're using, or if y'all think some erroneous input is making its manner into library code and blowing upwards.

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

Follow the Clues: How to Diagnose the Error

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

Hither'southward the full text of that file:

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

Line 9 is this one:

And only for reference, here's that error bulletin again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's break this down!

  • TypeError is the kind of fault

At that place are a handful of built-in error types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid blazon." (this part is, IMO, the least useful part of the error bulletin)

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

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

The about common is probably the . operator.

As in user.name, to admission the name holding 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[5] or items['map'].

You might wonder why the error isn't more than specific, like "Cannot read function `map` of undefined" – merely call back, the JS interpreter has no idea what we meant that type to exist. It doesn't know it was supposed to exist an array, or that map is a part. It didn't get that far, because items is undefined.

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

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

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

Information technology would be way more useful if the error could say "Cannot read property `map` of items". Sadly it doesn't say that. It tells yous 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, hither)
  • scan that line looking for .map
  • wait at the variable/expression/whatsoever immediately before the .map and exist very suspicious of it.

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

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

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

Fixing This in the Real World

Of grade this example is tiny and contrived, with a simple mistake, and it'due south colocated very shut to the site of the fault. These ones are the easiest to set!

There are a ton of potential causes for an error like this, though.

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

Or maybe you lot did laissez passer that prop, but the value existence passed in is really undefined or goose egg.

If it's a local country variable, maybe you're initializing the state as undefined – useState(), written similar that with no arguments, will do exactly this!

If information technology's a prop coming from Redux, perchance your mapStateToProps is missing the value, or has a typo.

Any the case, though, the procedure is the same: showtime where the error is and piece of work backwards, verifying your assumptions at each signal the variable is used. Throw in some panel.logsouthward or use the debugger to inspect the intermediate values and figure out why it's undefined.

Y'all'll become information technology fixed! Adept luck :)

Success! Now check your e-mail.

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

Pure React plant

Learn to think in React

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

Outset learning Pure React now

Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'g 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

girdlestonehaversidne.blogspot.com

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

0 Response to "Uncaught (in Promise) Typeerror: Cannot Read Property 'map' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel