How to Correct Uncaught Typeerror: Cannot Read Property 'jquery' of Undefined

Got an error similar this in your React component?

Cannot read belongings `map` of undefined

In this post we'll talk most how to ready this one specifically, and along 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 mistake, and ultimately how to fix it.

The Quick Set up

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

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

Make sure to initialize the state properly. That ways if it volition eventually exist an array, employ useState([]) instead of something like useState() or useState(null).

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

How to Find the Error

Get-go gild of business is to effigy out where the error is.

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

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
vii | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div central = {item . id} >
eleven | {item . proper noun}
12 | < / div >

Look for the file and the line number outset.

Here, that's /src/App.js and line 9, taken from the low-cal gray text in a higher place the code block.

btw, when y'all come across something similar /src/App.js:9:13, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

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

The lines are in order of execution, with the most recent first.

Hither'southward the stack trace for this fault, 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.development.js:16114)                              at performUnitOfWork (react-dom.evolution.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.development.js:17211)                              at                            eval                              (react-dom.development.js:17610)                              at unbatchedUpdates (react-dom.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:seven)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.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.e.              <              computed              >                              [every bit adjacent] (runtime.js:97)                              at t (asyncToGenerator.js:iii)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore nearly of it! The first 2 lines are all we intendance about here.

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

Let'due south decode a couple of these lines:

Hither we have:

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

Let'south await 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'south a big file!)

Ignore Files That Aren't Yours

I already mentioned this but I wanted to state it explictly: when you're looking at a stack trace, you can almost e'er ignore any lines that refer to files that are outside your codebase, like ones from a library.

Unremarkably, that means you'll pay attention to only the outset few lines.

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

There are some cases where you do care about the full stack, simply they're few and far betwixt, in my feel. Things similar… if you lot suspect a bug in the library you lot're using, or if you think some erroneous input is making its way into library code and bravado upwards.

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

Follow the Clues: How to Diagnose the Error

So the stack trace told united states of america where to wait: line nine of App.js. Let'southward open that upwardly.

Here's the full text of that file:

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

Line 9 is this 1:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Permit'southward break this downward!

  • TypeError is the kind of error

There are a scattering of built-in error types. MDN says TypeError "represents an mistake that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the to the lowest degree useful part of the error message)

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

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

The about common is probably the . operator.

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

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

At that place'south as well brackets (aka square brackets, []) for accessing items in an assortment, similar items[5] or items['map'].

Y'all might wonder why the error isn't more than specific, like "Cannot read office `map` of undefined" – simply recollect, the JS interpreter has no idea what nosotros meant that type to be. It doesn't know it was supposed to be an assortment, or that map is a function. It didn't go that far, considering items is undefined.

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

This one is some other great clue. Combined with the previous flake, you tin be pretty sure yous should be looking for .map somewhere on this line.

  • of undefined is a clue about 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. Information technology tells y'all the value of that variable instead.

So now you lot can piece this all together:

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

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

In our little example, the only other occurrence of items is line iv:

This defines the variable but it doesn't set up it to annihilation, which means its value is undefined. There's the problem. Fix that, and you ready the error!

Fixing This in the Real World

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

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

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

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

If it'southward a local country variable, maybe yous're initializing the land equally undefined – useState(), written like that with no arguments, will do exactly this!

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

Whatsoever the case, though, the process is the aforementioned: start where the mistake is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some console.logs or employ the debugger to audit the intermediate values and figure out why information technology's undefined.

You lot'll get it fixed! Good luck :)

Success! Now check your e-mail.

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

Pure React plant

Learn 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'southward Pure React is a piece of work of enormous clarity and depth. Hats off. I'1000 a React trainer in London and would thoroughly recommend this to all front devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

abbottpiculd.blogspot.com

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

0 Response to "How to Correct Uncaught Typeerror: Cannot Read Property 'jquery' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel