Error in : Typeerror: Cannot Read Property 'kind' of Undefined

Got an mistake like this in your React component?

Cannot read property `map` of undefined

In this mail service we'll talk nearly how to fix this 1 specifically, and along the way you'll learn how to approach fixing errors in general.

Nosotros'll encompass how to read a stack trace, how to translate the text of the error, and ultimately how to fix it.

The Quick Fix

This mistake ordinarily means you're trying to apply .map on an array, only that assortment isn't defined yet.

That'due south frequently because the array is a piece of undefined country or an undefined prop.

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

Let's look at how nosotros can translate an mistake bulletin and track downwards where information technology happened and why.

How to Observe the Error

Kickoff social club of business is to effigy out where the error is.

If you're using Create React App, it 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} >
eleven | {item . name}
12 | < / div >

Look for the file and the line number starting time.

Here, that'due south /src/App.js and line 9, taken from the lite gray text above the code block.

btw, when you see something like /src/App.js:ix: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, y'all'll need to read the stack trace to figure out where the fault was.

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

The lines are in gild of execution, with the virtually recent beginning.

Here's the stack trace for this error, with the only 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.evolution.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              $ane                              (react-dom.evolution.js:16114)                              at performUnitOfWork (react-dom.evolution.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.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.return (react-dom.development.js:17672)                              at evaluate (index.js:7)                              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              >                              [equally next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore most of it! The first 2 lines are all nosotros care about here.

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

Let's decode a couple of these lines:

Here we have:

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

Permit's look at another 1:

                          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, you can virtually always ignore whatsoever lines that refer to files that are outside your codebase, like ones from a library.

Usually, that means you lot'll pay attention to simply the outset few lines.

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

There are some cases where you do intendance near the full stack, just they're few and far between, in my experience. Things similar… if you lot doubtable a bug in the library you're using, or if you recollect some erroneous input is making its way into library code and bravado upward.

The vast bulk of the time, though, the bug will exist in your own code ;)

Follow the Clues: How to Diagnose the Error

Then the stack trace told u.s. where to await: line nine of App.js. Let's open that up.

Here'south 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              (              item                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .proper noun              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line nine is this i:

And just for reference, here's that error message once more:

                          TypeError: Cannot read holding 'map' of undefined                                    

Let's intermission this down!

  • TypeError is the kind of error

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

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

This is a good inkling! At that place are only a few ways to read properties in JavaScript.

The most common is probably the . operator.

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

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

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

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

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

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

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

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

Then now you can piece this all together:

  • detect the line that the mistake occurred on (line ix, here)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately before the .map and be very suspicious of it.

Once y'all know which variable to wait at, y'all tin read through the function looking for where it comes from, and whether it's initialized.

In our piddling instance, the only other occurrence of items is line four:

This defines the variable but information technology doesn't set it to anything, which means its value is undefined. There's the problem. Fix that, and you fix the fault!

Fixing This in the Real World

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

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

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

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

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

If information technology'south a prop coming from Redux, maybe your mapStateToProps is missing the value, or has a typo.

Whatever the case, though, the process is the aforementioned: start where the fault is and work backwards, verifying your assumptions at each bespeak the variable is used. Throw in some console.logs or utilize the debugger to inspect the intermediate values and figure out why it's undefined.

You'll get it fixed! Expert luck :)

Success! Now cheque your e-mail.

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

Pure React plant

Learn to retrieve in React

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

Outset learning Pure React at present

Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'k 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

cokerthroaked75.blogspot.com

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

0 Response to "Error in : Typeerror: Cannot Read Property 'kind' of Undefined"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel