Jest Typeerror Cannot Read Property of Undefined

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to fix this one specifically, and forth the way yous'll learn how to arroyo fixing errors in full general.

Nosotros'll comprehend how to read a stack trace, how to interpret the text of the error, and ultimately how to prepare it.

The Quick Gear up

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

That's ofttimes because the assortment is a slice of undefined land or an undefined prop.

Make certain to initialize the state properly. That ways if it will eventually be an assortment, employ useState([]) instead of something like useState() or useState(zippo).

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

How to Find the Error

Get-go order of concern is to figure out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div cardinal = {item . id} >
11 | {item . name}
12 | < / div >

Look for the file and the line number commencement.

Here, that's /src/App.js and line 9, taken from the light grey text above the code cake.

btw, when you lot come across something similar /src/App.js:9:xiii, the fashion 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 mistake was.

These always look long and intimidating, only the trick is that ordinarily you can ignore near of information technology!

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

Hither'south 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.evolution.js:2804)                              at beginWork              $1                              (react-dom.evolution.js:16114)                              at performUnitOfWork (react-dom.evolution.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.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:vii)                              at z (eval.js:42)                              at 1000.evaluate (transpiled-module.js:692)                              at exist.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 adjacent] (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 commencement 2 lines are all nosotros intendance about here.

The first line is the error message, and every line after that spells out the unwound stack of function calls that led to information technology.

Let's 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 mistake occurred

Let'south wait at another ane:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the name of the office where this happened
  • react-dom.evolution.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 land it explictly: when you lot're looking at a stack trace, yous can most always ignore any lines that refer to files that are outside your codebase, like ones from a library.

Ordinarily, that means y'all'll pay attention to merely the get-go few lines.

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

There are some cases where you do care about the full stack, but they're few and far between, in my experience. Things like… if you suspect a bug in the library y'all're using, or if yous recollect some erroneous input is making its way into library code and blowing up.

The vast majority of the fourth dimension, though, the bug will be in your own code ;)

Follow the Clues: How to Diagnose the Error

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

Here's the total text of that file:

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

Line nine is this ane:

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

                          TypeError: Cannot read holding 'map' of undefined                                    

Let'south break this down!

  • TypeError is the kind of fault

In that location 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 part is, IMO, the to the lowest degree useful office of the error message)

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

This is a practiced clue! There are but a few ways to read backdrop 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 access the map holding of the items object.

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

You lot might wonder why the error isn't more than specific, like "Cannot read office `map` of undefined" – but remember, the JS interpreter has no thought what we meant that type to exist. It doesn't know information technology was supposed to be an array, or that map is a function. It didn't go that far, because items is undefined.

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

This one is another great inkling. Combined with the previous fleck, you tin be pretty sure y'all should be looking for .map somewhere on this line.

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

It would be mode 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 now you tin can slice this all together:

  • observe the line that the error occurred on (line nine, here)
  • 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 lot can read through the function looking for where it comes from, and whether it's initialized.

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

This defines the variable only it doesn't set it to annihilation, which ways its value is undefined. In that location's the trouble. Fix that, and you fix the error!

Fixing This in the Real World

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

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

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

Or maybe you did laissez passer that prop, merely the value existence passed in is really undefined or null.

If it'southward a local state variable, maybe you're initializing the state as undefined – useState(), written similar that with no arguments, volition do 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: commencement where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some panel.logs or utilize the debugger to inspect the intermediate values and figure out why information technology'south undefined.

You'll become it fixed! Good luck :)

Success! Now check your email.

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

Pure React plant

Learn to call back 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'south 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 front end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

prevatteaddis1944.blogspot.com

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

0 Response to "Jest Typeerror Cannot Read Property of Undefined"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel