React Native + Cannot Read Property Apply of Undefined

Got an error like this in your React component?

Cannot read holding `map` of undefined

In this postal service we'll talk about how to fix this one specifically, and along the style you'll learn how to arroyo 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 fix it.

The Quick Fix

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

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

Brand sure to initialize the state properly. That means if information technology will eventually be an array, apply useState([]) instead of something like useState() or useState(nil).

Let's await at how we can interpret an error message and rail downward where information technology happened and why.

How to Discover the Error

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

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

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> nine | {items . map((item) => (
| ^
ten | < div key = {detail . id} >
11 | {item . proper noun}
12 | < / div >

Wait for the file and the line number starting time.

Here, that'southward /src/App.js and line ix, taken from the light grey text to a higher place the lawmaking block.

btw, when yous 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 demand to read the stack trace to figure out where the error was.

These always look long and intimidating, simply the trick is that usually you tin ignore most of it!

The lines are in guild of execution, with the most contempo first.

Hither'south the stack trace for this fault, with the just of import 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.evolution.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.js:2770)                              at invokeGuardedCallback (react-dom.evolution.js:2804)                              at beginWork              $one                              (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.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.development.js:14770)                              at updateContainer (react-dom.development.js:17211)                              at                            eval                              (react-dom.evolution.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (alphabetize.js:vii)                              at z (eval.js:42)                              at Chiliad.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.east.              <              computed              >                              [as adjacent] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore most of it! The first 2 lines are all we intendance well-nigh here.

The first line is the mistake bulletin, and every line subsequently that spells out the unwound stack of function calls that led to it.

Let's decode a couple of these lines:

Hither we have:

  • App is the proper noun of our component function
  • App.js is the file where it appears
  • 9 is the line of that file where the mistake occurred

Let's look at some other ane:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper name of the function 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 information technology explictly: when you're looking at a stack trace, you tin 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 list until it starts to veer into file names you don't recognize.

At that place are some cases where you exercise care near the total stack, merely they're few and far between, in my experience. Things similar… if you doubtable a issues in the library you're using, or if yous think some erroneous input is making its fashion into library lawmaking and bravado up.

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

Follow the Clues: How to Diagnose the Mistake

So the stack trace told us where to look: line nine of App.js. Allow's open that upwardly.

Here's the full text of that file:

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

Line 9 is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Allow'due south break this downwards!

  • TypeError is the kind of mistake

There are a handful of born error types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid type." (this role is, IMO, the to the lowest degree useful part of the error message)

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

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

The most common is probably the . operator.

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

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

There'south likewise brackets (aka foursquare brackets, []) for accessing items in an assortment, similar items[v] or items['map'].

Yous might wonder why the fault isn't more specific, like "Cannot read office `map` of undefined" – but recall, the JS interpreter has no idea what we meant that type to be. Information technology doesn't know it was supposed to exist an array, or that map is a office. It didn't get that far, because items is undefined.

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

This one is another groovy inkling. Combined with the previous bit, y'all can be pretty certain you lot should exist looking for .map somewhere on this line.

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

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

So now you can slice this all together:

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

Once y'all know which variable to wait at, you can read through the function looking for where it comes from, and whether it'south initialized.

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

This defines the variable only it doesn't prepare it to anything, which ways its value is undefined. There's the problem. Prepare that, and you gear up the fault!

Fixing This in the Real Globe

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

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

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

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

If information technology's a local state variable, maybe you're initializing the land as 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.

Whatsoever the case, though, the process is the same: first where the error is and work backwards, verifying your assumptions at each bespeak the variable is used. Throw in some panel.logs or apply the debugger to inspect the intermediate values and effigy out why it's undefined.

You'll get it fixed! Skillful luck :)

Success! Now check your email.

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

Pure React plant

Learn to think in React

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

Outset learning Pure React now

Dave Ceddia'southward 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 stop devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

araizagrandsid.blogspot.com

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

0 Response to "React Native + Cannot Read Property Apply of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel