Pm Err! Cannot Read Property 'match' of Undefined

Got an fault similar this in your React component?

Cannot read belongings `map` of undefined

In this post we'll talk nigh how to fix this one specifically, and forth the way yous'll learn how to approach fixing errors in general.

We'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 error commonly means y'all're trying to use .map on an assortment, but that assortment isn't defined even so.

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

Make sure to initialize the state properly. That means if information technology will somewhen be an array, employ useState([]) instead of something like useState() or useState(nada).

Let's look at how nosotros can translate an error message and track down where it happened and why.

How to Find the Error

Start order of business is to effigy out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          half-dozen |                                                      render                                      (                                
7 | < div className = "App" >
8 | < h1 > Listing of Items < / h1 >
> 9 | {items . map((item) => (
| ^
ten | < div primal = {item . id} >
11 | {particular . name}
12 | < / div >

Look for the file and the line number offset.

Here, that's /src/App.js and line nine, taken from the lite gray text to a higher place the code block.

btw, when you encounter something like /src/App.js:nine:xiii, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If y'all're looking at the browser console instead, you lot'll need to read the stack trace to figure out where the error was.

These always await long and intimidating, but the trick is that usually you tin can ignore nigh of information technology!

The lines are in order of execution, with the near recent commencement.

Here'southward the stack trace for this error, with the simply important lines highlighted:

                                          TypeError: Cannot                                read                                  belongings                                'map'                                  of undefined                                                              at App (App.js:nine)                                            at renderWithHooks (react-dom.development.js:10021)                              at mountIndeterminateComponent (react-dom.evolution.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              $ane                              (react-dom.development.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.development.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.return (react-dom.evolution.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (managing director.js:286)                              at exist.evaluateModule (director.js:257)                              at compile.ts:717                              at fifty (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.eastward.              <              computed              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said yous could ignore nigh of it! The first ii lines are all we care almost here.

The first line is the fault bulletin, and every line after that spells out the unwound stack of role calls that led to information technology.

Allow'due south decode a couple of these lines:

Here we have:

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

Let's look at another one:

                          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 only I wanted to country information technology explictly: when you're looking at a stack trace, you can almost always ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.

Ordinarily, that means you'll pay attending to only the first few lines.

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

There are some cases where y'all do intendance most the total stack, but they're few and far betwixt, in my experience. Things similar… if you doubtable a issues in the library you're using, or if y'all think some erroneous input is making its way into library code and bravado up.

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

Follow the Clues: How to Diagnose the Error

So the stack trace told the states 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"              ;              consign                                          default                                          function                                          App              ()                                          {                                          let                                          items              ;                                          render                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              Listing of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              particular              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let's intermission this downwardly!

  • 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 blazon." (this part is, IMO, the least useful role of the fault message)

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

This is a good clue! There are only a few means to read backdrop in JavaScript.

The nearly common is probably the . operator.

As in user.proper noun, to admission the name property of the user object.

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

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

You might wonder why the error isn't more specific, like "Cannot read part `map` of undefined" – just remember, the JS interpreter has no idea what nosotros meant that type to be. 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 i is another great clue. Combined with the previous scrap, you tin can exist pretty sure you should exist 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 lot the value of that variable instead.

So now you can piece this all together:

  • observe the line that the error occurred on (line 9, hither)
  • scan that line looking for .map
  • await at the variable/expression/whatsoever immediately earlier the .map and be very suspicious of information technology.

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

In our trivial instance, the only other occurrence of items is line 4:

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

Fixing This in the Real World

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

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

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

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

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

If it'due south a prop coming from Redux, maybe your mapStateToProps is missing the value, or has a typo.

Whatever the instance, though, the process is the same: start where the error is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.logs or utilize the debugger to inspect the intermediate values and effigy out why it's undefined.

Y'all'll become it fixed! Good luck :)

Success! At present check your email.

Learning React can be a struggle — and 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

Acquire to think in React

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

Start learning Pure React now

Dave Ceddia'due south Pure React is a work of enormous clarity and depth. Hats off. I'k a React trainer in London and would thoroughly recommend this to all forepart cease devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

thurstonchas1965.blogspot.com

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

0 Response to "Pm Err! Cannot Read Property 'match' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel