Javascript Cannot Read Property 'foreach' of Undefined

Got an mistake similar this in your React component?

Cannot read property `map` of undefined

In this postal service we'll talk virtually how to fix this ane specifically, and along the mode y'all'll learn how to approach fixing errors in general.

Nosotros'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 usually ways you lot're trying to use .map on an array, only that assortment isn't defined yet.

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

Make certain to initialize the state properly. That means if it will eventually exist an array, utilize useState([]) instead of something like useState() or useState(nothing).

Let's expect at how nosotros tin interpret an error message and track downwards where information technology happened and why.

How to Observe the Mistake

First order of business organization is to figure out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          half-dozen |                                                      return                                      (                                
vii | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> ix | {items . map((item) => (
| ^
10 | < div key = {item . id} >
xi | {item . proper noun}
12 | < / div >

Look for the file and the line number first.

Hither, that's /src/App.js and line 9, taken from the light greyness text above the code block.

btw, when you lot see something like /src/App.js:9:13, 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 ever wait long and intimidating, merely the fob is that usually yous tin can ignore almost of it!

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

Here's 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.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.development.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.development.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.render (react-dom.evolution.js:17672)                              at evaluate (index.js:vii)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.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.due east.              <              computed              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:iii)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore virtually of information technology! The start 2 lines are all we care about here.

The outset line is the fault message, and every line afterward that spells out the unwound stack of office calls that led to information technology.

Let'southward 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 fault occurred

Permit's expect at another ane:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the part where this happened
  • react-dom.evolution.js is the file
  • 15008 is the line number (information technology'due south a large file!)

Ignore Files That Aren't Yours

I already mentioned this but I wanted to land it explictly: when you're looking at a stack trace, you can almost ever ignore whatever lines that refer to files that are exterior your codebase, similar ones from a library.

Usually, that means y'all'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 yous do care most the total stack, just they're few and far betwixt, in my experience. Things like… if yous suspect a bug in the library you're using, or if you recall some erroneous input is making its way into library code and blowing upwardly.

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

Follow the Clues: How to Diagnose the Mistake

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

Here's the full text of that file:

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

Line nine is this one:

And simply for reference, here's that error message again:

                          TypeError: Cannot read belongings 'map' of undefined                                    

Let's break this down!

  • TypeError is the kind of fault

There are a handful of congenital-in fault 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 part of the mistake message)

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

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

The almost common is probably the . operator.

Equally in user.name, to admission the name property of the user object.

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

In that location'southward also brackets (aka square brackets, []) for accessing items in an array, similar items[5] or items['map'].

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

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

This one is some other not bad clue. Combined with the previous scrap, you tin be pretty sure yous should be looking for .map somewhere on this line.

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

It would be fashion more useful if the fault could say "Cannot read belongings `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.

So now you tin can piece this all together:

  • find the line that the error occurred on (line ix, hither)
  • scan that line looking for .map
  • look at the variable/expression/whatsoever immediately before the .map and be very suspicious of it.

One time you know which variable to wait at, you can read through the function looking for where information technology comes from, and whether it'southward initialized.

In our piffling case, the only other occurrence of items is line iv:

This defines the variable but information technology doesn't set it to anything, which means its value is undefined. There'due south the problem. Ready that, and you gear up the error!

Fixing This in the Real World

Of grade this example is tiny and contrived, with a simple mistake, and it's colocated very close to the site of the error. These ones are the easiest to gear up!

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

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

Or perhaps you did pass that prop, only the value being passed in is really undefined or cypher.

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

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

Whatever the instance, though, the process is the same: start where the mistake is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouth or use the debugger to audit the intermediate values and effigy out why information technology's undefined.

Y'all'll get it stock-still! Proficient luck :)

Success! Now cheque your email.

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

Pure React plant

Learn to think in React

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

Start learning Pure React now

Dave Ceddia's 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 forepart end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

brzozowskibectionet.blogspot.com

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

0 Response to "Javascript Cannot Read Property 'foreach' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel