Uncaught Type Error Cannot Read Property 'rank' of Undefined

Got an error similar this in your React component?

Cannot read holding `map` of undefined

In this postal service we'll talk about how to fix this i specifically, and along the manner 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 error, and ultimately how to prepare it.

The Quick Set

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

That'due south oft considering the array is a piece of undefined state or an undefined prop.

Make sure to initialize the land properly. That ways if it will eventually be an array, use useState([]) instead of something like useState() or useState(null).

Permit'south look at how we tin can interpret an error message and track downward where it happened and why.

How to Discover the Error

First social club of business is to effigy out where the mistake is.

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

TypeError

Cannot read property 'map' of undefined

App

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

Look for the file and the line number offset.

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

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

How to Read the Stack Trace

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

These ever look long and intimidating, simply the play a joke on is that usually you can ignore most of it!

The lines are in guild of execution, with the about contempo first.

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: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              $one                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.development.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.evolution.js:15268)                              at performSyncWorkOnRoot (react-dom.evolution.js:15008)                              at scheduleUpdateOnFiber (react-dom.development.js:14770)                              at updateContainer (react-dom.evolution.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:seven)                              at z (eval.js:42)                              at Thou.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (director.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [every bit next] (runtime.js:97)                              at t (asyncToGenerator.js:iii)                              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 care about here.

The first line is the error message, and every line afterwards that spells out the unwound stack of role calls that led to it.

Allow's decode a couple of these lines:

Here nosotros accept:

  • App is the proper name of our component role
  • App.js is the file where it appears
  • nine is the line of that file where the error occurred

Let's look at some other one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the name of the role 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 simply I wanted to state it explictly: when y'all're looking at a stack trace, y'all tin almost ever ignore any lines that refer to files that are exterior your codebase, like ones from a library.

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

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

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

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

Follow the Clues: How to Diagnose the Mistake

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

Here's the full text of that file:

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

Line 9 is this ane:

And just for reference, here's that fault message over again:

                          TypeError: Cannot read property 'map' of undefined                                    

Permit'due south intermission this down!

  • TypeError is the kind of error

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

  • Cannot read belongings ways the lawmaking was trying to read a belongings.

This is a skillful inkling! There are only a few ways to read properties in JavaScript.

The nearly common is probably the . operator.

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

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

In that location'southward likewise brackets (aka foursquare brackets, []) for accessing items in an array, like items[5] or items['map'].

You might wonder why the error isn't more specific, like "Cannot read part `map` of undefined" – simply recall, the JS interpreter has no thought what we meant that type to be. Information technology doesn't know it was supposed to be an array, or that map is a office. It didn't get that far, because items is undefined.

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

This ane is another bang-up clue. Combined with the previous bit, you lot tin be pretty sure you lot should be looking for .map somewhere on this line.

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

So at present you tin piece this all together:

  • detect the line that the mistake 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 it.

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

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

This defines the variable just it doesn't set information technology to anything, which ways its value is undefined. In that location'due south the trouble. Fix that, and you fix the mistake!

Fixing This in the Existent World

Of course this instance is tiny and contrived, with a uncomplicated error, and it's colocated very shut to the site of the mistake. 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 it downward.

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 you lot'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, maybe your mapStateToProps is missing the value, or has a typo.

Any the case, though, the process is the aforementioned: starting time where the error is and work backwards, verifying your assumptions at each signal the variable is used. Throw in some console.logs or apply the debugger to audit the intermediate values and effigy out why information technology'due south undefined.

You'll get it stock-still! Proficient luck :)

Success! Now check your email.

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

Pure React plant

Learn to think in React

  • ninety+ screencast lessons
  • Total transcripts and closed captions
  • All the lawmaking from the lessons
  • Developer interviews

Beginning learning Pure React now

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

Alan Lavender

Alan Lavender

@lavenderlens

bauerwhours.blogspot.com

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

0 Response to "Uncaught Type Error Cannot Read Property 'rank' of Undefined"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel