React Native Cannot Read Property 'bind' 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 set up this one specifically, and along the way you'll acquire how to approach fixing errors in full general.

We'll cover how to read a stack trace, how to interpret the text of the mistake, and ultimately how to fix it.

The Quick Prepare

This fault normally means you're trying to apply .map on an array, only that array isn't defined still.

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

Make sure to initialize the state properly. That means if it volition eventually be an array, use useState([]) instead of something like useState() or useState(aught).

Let'southward look at how we can interpret an fault message and track downward where it happened and why.

How to Find the Error

Showtime order of business is to figure out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

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

Look for the file and the line number beginning.

Here, that'south /src/App.js and line 9, taken from the calorie-free greyness text above the code block.

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

These always expect long and intimidating, merely the trick is that unremarkably you can ignore most of it!

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

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

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

I wasn't kidding when I said you could ignore almost of it! The starting time 2 lines are all nosotros intendance about here.

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

Permit'due south decode a couple of these lines:

Here we accept:

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

Permit'due south look at another one:

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

Ignore Files That Aren't Yours

I already mentioned this but I wanted to state information technology explictly: when yous're looking at a stack trace, you can almost always ignore whatsoever lines that refer to files that are exterior your codebase, like ones from a library.

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

Scan down the list until information technology starts to veer into file names y'all don't recognize.

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

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

Follow the Clues: How to Diagnose the Error

Then the stack trace told the states where to look: line ix of App.js. Permit's open that up.

Hither's the full text of that file:

                          import                                          "./styles.css"              ;              consign                                          default                                          part                                          App              ()                                          {                                          let                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              Listing of Items              </              h1              >                                          {              items              .              map              (              detail                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this one:

And merely for reference, hither's that error message again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's break this down!

  • TypeError is the kind of error

There are a scattering of congenital-in error 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 error message)

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

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

The most common is probably the . operator.

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

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

There'southward too brackets (aka foursquare brackets, []) for accessing items in an assortment, like items[5] or items['map'].

You might wonder why the error isn't more than specific, like "Cannot read function `map` of undefined" – but remember, the JS interpreter has no thought what nosotros meant that blazon to exist. It 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 another great clue. Combined with the previous fleck, you tin can be pretty sure yous should exist looking for .map somewhere on this line.

  • of undefined is a clue nigh 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 you the value of that variable instead.

Then now you can piece this all together:

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

Once you know which variable to look at, yous tin read through the function looking for where it comes from, and whether information technology'due south initialized.

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

This defines the variable but information technology doesn't gear up it to anything, which means its value is undefined. There'southward the problem. Fix that, and you lot ready 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 mistake. These ones are the easiest to fix!

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

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

Or peradventure yous did pass that prop, but the value beingness passed in is actually undefined or null.

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

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

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

You'll get information technology fixed! Good luck :)

Success! At present check your email.

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

Pure React plant

Learn to think in React

  • xc+ screencast lessons
  • Full transcripts and closed captions
  • All the lawmaking from the lessons
  • Developer interviews

Start learning Pure React now

Dave Ceddia's Pure React is a piece of work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

lopezarecas.blogspot.com

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

0 Response to "React Native Cannot Read Property 'bind' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel