Error in Event Handler: Typeerror: Cannot Read Property 'getcurrent' of Undefined

Got an mistake like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk nigh how to prepare this one specifically, and along the fashion you'll acquire how to approach fixing errors in general.

We'll encompass how to read a stack trace, how to interpret the text of the error, and ultimately how to prepare information technology.

The Quick Fix

This error usually means you're trying to use .map on an array, but that array isn't defined still.

That'southward frequently considering the array is a piece of undefined state or an undefined prop.

Make sure to initialize the state properly. That means if it will somewhen be an assortment, use useState([]) instead of something similar useState() or useState(null).

Let'southward expect at how we tin interpret an error message and track down where it happened and why.

How to Find the Error

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

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          half dozen |                                                      return                                      (                                
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> 9 | {items . map((detail) => (
| ^
10 | < div key = {particular . id} >
11 | {particular . name}
12 | < / div >

Look for the file and the line number first.

Here, that's /src/App.js and line 9, taken from the light gray text to a higher place the code cake.

btw, when you see something like /src/App.js:ix:13, the mode to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If yous're looking at the browser console instead, you lot'll demand to read the stack trace to figure out where the fault was.

These e'er wait long and intimidating, but the play a joke on is that usually you tin can ignore most of information technology!

The lines are in lodge of execution, with the virtually contempo get-go.

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

                                          TypeError: Cannot                                read                                  property                                '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.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.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.evolution.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.development.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.render (react-dom.development.js:17672)                              at evaluate (alphabetize.js:vii)                              at z (eval.js:42)                              at Yard.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.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.e.              <              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 near of it! The first ii lines are all we care about here.

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

Let'south decode a couple of these lines:

Hither we accept:

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

Allow's wait at another one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the proper noun 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, y'all tin can virtually e'er ignore any lines that refer to files that are outside your codebase, like ones from a library.

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

Browse downwardly the list until information technology starts to veer into file names you don't recognize.

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

The vast majority of the time, though, the problems will be in your own lawmaking ;)

Follow the Clues: How to Diagnose the Fault

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

Here's the total text of that file:

                          import                                          "./styles.css"              ;              export                                          default                                          office                                          App              ()                                          {                                          let                                          items              ;                                          render                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line ix is this one:

And just for reference, here'south that error message over again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's break this down!

  • TypeError is the kind of mistake

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

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

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

The about common is probably the . operator.

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

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

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

You might wonder why the fault 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. It doesn't know it was supposed to be an array, or that map is a function. It didn't get that far, because items is undefined.

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

This one is another bully inkling. Combined with the previous bit, you can exist pretty sure you should be looking for .map somewhere on this line.

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

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

So now you can piece this all together:

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

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

In our fiddling example, the only other occurrence of items is line 4:

This defines the variable but it doesn't set it to anything, which means its value is undefined. In that location'south the problem. Fix that, and y'all prepare the fault!

Fixing This in the Existent Earth

Of form this example is tiny and contrived, with a simple fault, and information technology'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 error like this, though.

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

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

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

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

Any the case, though, the process is the aforementioned: beginning where the error is and piece of work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and figure out why it's undefined.

You'll go it stock-still! Good luck :)

Success! At present check your email.

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

Larn to call up 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'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 end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavander

@lavenderlens

hohmandoperis.blogspot.com

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

Belum ada Komentar untuk "Error in Event Handler: Typeerror: Cannot Read Property 'getcurrent' of Undefined"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel