Typeerror: Cannot Read Property 'clear' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this mail service we'll talk about how to set this one specifically, and along the way you lot'll learn how to arroyo fixing errors in general.

We'll comprehend how to read a stack trace, how to interpret the text of the fault, and ultimately how to set up it.

The Quick Fix

This error usually means you lot're trying to use .map on an assortment, just that array isn't divers notwithstanding.

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

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

Let'due south await at how nosotros can interpret an error bulletin and track down where it happened and why.

How to Find the Error

Kickoff guild of business is to figure out where the mistake is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          vi |                                                      return                                      (                                
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> ix | {items . map((item) => (
| ^
10 | < div key = {particular . id} >
11 | {item . proper name}
12 | < / div >

Look for the file and the line number first.

Here, that'due south /src/App.js and line 9, taken from the light gray text to a higher place the lawmaking block.

btw, when you 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, yous'll need to read the stack trace to figure out where the fault was.

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

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

Here's the stack trace for this error, with the but 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.development.js:12143)                              at beginWork (react-dom.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.development.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.evolution.js:2770)                              at invokeGuardedCallback (react-dom.development.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.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 K.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (manager.js:257)                              at compile.ts:717                              at 50 (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [equally next] (runtime.js:97)                              at t (asyncToGenerator.js:three)                              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 nearly hither.

The first line is the error bulletin, and every line after that spells out the unwound stack of office 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 information technology appears
  • 9 is the line of that file where the error occurred

Let's wait at some other 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's a big file!)

Ignore Files That Aren't Yours

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

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

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

There are some cases where you do care about the full stack, but they're few and far betwixt, in my feel. Things like… if yous suspect a bug in the library you're using, or if you call back some erroneous input is making its fashion into library code and blowing upwardly.

The vast bulk of the time, though, the bug volition be in your own code ;)

Follow the Clues: How to Diagnose the Fault

So the stack trace told us where to look: line ix of App.js. Let'southward open that upwards.

Here's the full text of that file:

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

Line nine is this one:

And but for reference, here's that error message once again:

                          TypeError: Cannot read holding 'map' of undefined                                    

Let'due south break this downwardly!

  • TypeError is the kind of error

There are a handful of built-in error types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid type." (this role is, IMO, the least useful part of the error message)

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

This is a skillful clue! In that location are only a few means to read properties in JavaScript.

The most common is probably the . operator.

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

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

In that location's also brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].

You might wonder why the error isn't more than specific, similar "Cannot read function `map` of undefined" – only remember, the JS interpreter has no idea what we meant that type to be. It doesn't know it was supposed to exist an array, or that map is a function. It didn't get that far, because items is undefined.

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

This one is some other dandy clue. Combined with the previous flake, yous can exist 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 property `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.

So at present y'all tin piece this all together:

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

One time y'all know which variable to await at, y'all can read through the part looking for where it comes from, and whether it'due south initialized.

In our little instance, 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. There'due south the trouble. Prepare that, and you lot gear up the error!

Fixing This in the Real World

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

At that place are a ton of potential causes for an error like this, though.

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

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

If it'due south a local state variable, maybe y'all're initializing the country equally undefined – useState(), written like that with no arguments, will practise 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 same: get-go where the mistake is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.logdue south or use the debugger to inspect the intermediate values and figure out why it's undefined.

Yous'll become information technology fixed! Good luck :)

Success! At present check your email.

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

Pure React plant

Learn to think in React

  • xc+ screencast lessons
  • Total transcripts and closed captions
  • All the code from the lessons
  • Developer interviews

Start learning Pure React at present

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

Alan Lavender

Alan Lavander

@lavenderlens

Typeerror: Cannot Read Property 'clear' of Undefined

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

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

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel