Typeerror: Cannot Read Property 'foreach' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to gear up this 1 specifically, and along the way you lot'll learn how to approach fixing errors in general.

We'll cover how to read a stack trace, how to translate the text of the error, and ultimately how to set up it.

The Quick Gear up

This mistake usually means you're trying to use .map on an array, just that assortment isn't defined all the same.

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

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

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

How to Find the Error

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

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

TypeError

Cannot read property 'map' of undefined

App

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

Look for the file and the line number first.

Here, that's /src/App.js and line 9, taken from the lite gray text above the lawmaking block.

btw, when you run into something like /src/App.js:9:13, 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, yous'll need to read the stack trace to effigy out where the error was.

These e'er await long and intimidating, but the fox is that ordinarily you can ignore most of it!

The lines are in social club of execution, with the near contempo start.

Here's the stack trace for this fault, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                'map'                                  of undefined                                                              at App (App.js:9)                                            at renderWithHooks (react-dom.evolution.js:10021)                              at mountIndeterminateComponent (react-dom.development.js:12143)                              at beginWork (react-dom.evolution.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.development.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.evolution.js:17609)                              at Object.render (react-dom.evolution.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (manager.js:286)                              at exist.evaluateModule (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [every bit 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 it! The showtime 2 lines are all we care near here.

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

Let's decode a couple of these lines:

Here nosotros have:

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

Allow's look at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the role where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it'due south a big file!)

Ignore Files That Aren't Yours

I already mentioned this simply I wanted to state it explictly: when you lot're looking at a stack trace, y'all can almost e'er ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.

Usually, that means you lot'll pay attention to just the first few lines.

Browse downward the list until it starts to veer into file names you don't recognize.

There are some cases where yous do care about the full stack, but they're few and far between, in my experience. Things like… if you lot suspect a bug in the library you're using, or if yous think some erroneous input is making its way into library code and blowing up.

The vast majority of the fourth dimension, though, the bug volition exist in your own lawmaking ;)

Follow the Clues: How to Diagnose the Error

And then the stack trace told us where to look: line ix of App.js. Allow'due south open that up.

Hither's the full text of that file:

                          import                                          "./styles.css"              ;              consign                                          default                                          function                                          App              ()                                          {                                          let                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          primal              =              {              item              .id              }              >                                          {              detail              .proper noun              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this ane:

And just for reference, here's that error message once more:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'south break this down!

  • TypeError is the kind of error

At that place are a handful of born error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid blazon." (this part is, IMO, the to the lowest degree useful role of the error bulletin)

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

This is a skillful inkling! There are just a few ways to read properties in JavaScript.

The almost common is probably the . operator.

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

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

There'southward also brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].

Yous 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. Information technology doesn't know information technology 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 bang-up inkling. Combined with the previous chip, you tin can be pretty sure you should be looking for .map somewhere on this line.

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

It would be way more useful if the error could say "Cannot read holding `map` of items". Sadly it doesn't say that. It tells yous the value of that variable instead.

So at present you lot can piece this all together:

  • find the line that the error occurred on (line 9, here)
  • scan that line looking for .map
  • wait at the variable/expression/whatever immediately before the .map and be very suspicious of it.

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

In our fiddling case, the merely other occurrence of items is line 4:

This defines the variable just it doesn't set it to anything, which ways its value is undefined. At that place'south the problem. Set that, and you ready the error!

Fixing This in the Existent World

Of course this example is tiny and contrived, with a elementary mistake, and it's colocated very close to the site of the fault. These ones are the easiest to prepare!

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 you lot forgot to pass information technology down.

Or maybe you did laissez passer that prop, just the value being passed in is actually undefined or nada.

If it'south a local state variable, peradventure yous're initializing the country 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 aforementioned: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or utilise the debugger to audit the intermediate values and figure out why it'southward undefined.

Yous'll get it fixed! Good luck :)

Success! Now check your electronic mail.

Learning React tin be a struggle — and so many libraries and tools!
My communication? Ignore all of them :)
For a step-by-stride approach, bank check out my Pure React workshop.

Pure React plant

Learn to recall in React

  • 90+ screencast lessons
  • Full transcripts and airtight captions
  • All the code 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'chiliad 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

downsspict1982.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel