Lompat ke konten Lompat ke sidebar Lompat ke footer

Vue Js Emit Typeerror: Cannot Read Property of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk almost how to set up this i specifically, and along the way you'll larn how to approach fixing errors in general.

Nosotros'll cover how to read a stack trace, how to interpret the text of the error, and ultimately how to fix information technology.

The Quick Ready

This error usually means you're trying to use .map on an array, just that array isn't defined however.

That's often because the assortment is a slice of undefined country or an undefined prop.

Brand sure to initialize the state properly. That means if it will somewhen be an array, utilise useState([]) instead of something like useState() or useState(goose egg).

Let'due south await at how nosotros tin interpret an error bulletin and track down where information technology happened and why.

How to Find the Fault

First order of business is to figure out where the error is.

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

TypeError

Cannot read belongings 'map' of undefined

App

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

Expect for the file and the line number starting time.

Here, that's /src/App.js and line 9, taken from the light grayness text higher up the lawmaking cake.

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

How to Read the Stack Trace

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

These always look long and intimidating, simply the trick is that usually you tin ignore most of information technology!

The lines are in order of execution, with the near recent outset.

Hither'southward the stack trace for this error, with the but important lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                'map'                                  of undefined                                                              at App (App.js:9)                                            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.development.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $1                              (react-dom.evolution.js:16114)                              at performUnitOfWork (react-dom.development.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.return (react-dom.evolution.js:17672)                              at evaluate (alphabetize.js:7)                              at z (eval.js:42)                              at Grand.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at exist.evaluateModule (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [as side by side] (runtime.js:97)                              at t (asyncToGenerator.js:iii)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said yous could ignore well-nigh of information technology! The kickoff 2 lines are all nosotros intendance about hither.

The showtime line is the error 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 proper noun of our component function
  • App.js is the file where information technology appears
  • 9 is the line of that file where the fault occurred

Permit's await at another one:

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

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

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

In that location are some cases where you do intendance about the full stack, just they're few and far between, in my experience. Things similar… if you lot suspect a bug in the library you lot're using, or if y'all think some erroneous input is making its way into library code and bravado up.

The vast majority of the time, though, the issues will be in your own code ;)

Follow the Clues: How to Diagnose the Fault

And so the stack trace told u.s. where to look: line 9 of App.js. Let's open that up.

Hither's the total text of that file:

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

Line 9 is this ane:

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

                          TypeError: Cannot read belongings 'map' of undefined                                    

Let'southward break this down!

  • TypeError is the kind of error

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

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

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

The nigh common is probably the . operator.

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

Or items.map, to admission the map belongings of the items object.

In that location'due south as well brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].

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

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

This i is another dandy inkling. Combined with the previous bit, yous can be pretty certain you should be looking for .map somewhere on this line.

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

It would exist style 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 you lot tin can piece this all together:

  • find the line that the error occurred on (line ix, here)
  • scan that line looking for .map
  • look at the variable/expression/any immediately earlier the .map and exist very suspicious of it.

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

In our little case, the just other occurrence of items is line 4:

This defines the variable but it doesn't prepare it to anything, which means its value is undefined. There's the problem. Ready that, and you fix the mistake!

Fixing This in the Existent Globe

Of form this instance 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!

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

Mayhap 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, but the value existence passed in is actually undefined or null.

If it'south a local state variable, possibly you're initializing the land every bit undefined – useState(), written like that with no arguments, will practise exactly this!

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

Whatever the case, though, the process is the same: start where the error is and piece of work backwards, verifying your assumptions at each signal the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and effigy out why information technology's undefined.

You lot'll get information technology fixed! Skillful luck :)

Success! Now bank 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, check out my Pure React workshop.

Pure React plant

Learn to call up in React

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

Offset learning Pure React at present

Dave Ceddia'due 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 forepart stop devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

hayesinupoppeired.blogspot.com

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

Posting Komentar untuk "Vue Js Emit Typeerror: Cannot Read Property of Undefined"