Skip to content Skip to sidebar Skip to footer

Cannot Read Property 'get' of Undefined at Eval Vue

Got an mistake similar this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to fix this ane specifically, and along the mode y'all'll learn how to arroyo fixing errors in general.

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

The Quick Fix

This error usually means yous're trying to use .map on an array, but that array isn't defined yet.

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

Make certain to initialize the state properly. That means if it will eventually exist an assortment, apply useState([]) instead of something similar useState() or useState(aught).

Let's look at how we can interpret an error bulletin and runway downward where it happened and why.

How to Detect the Error

First order of business organization 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 |                                                      render                                      (                                
7 | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div cardinal = {detail . id} >
11 | {item . proper name}
12 | < / div >

Look for the file and the line number first.

Here, that's /src/App.js and line ix, taken from the calorie-free gray text above the code block.

btw, when you see something like /src/App.js:9:thirteen, 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 mistake was.

These ever look long and intimidating, just the trick is that usually you tin can ignore most of it!

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

Here'due 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.evolution.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.evolution.js:2770)                              at invokeGuardedCallback (react-dom.evolution.js:2804)                              at beginWork              $1                              (react-dom.evolution.js:16114)                              at performUnitOfWork (react-dom.development.js:15339)                              at workLoopSync (react-dom.evolution.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.evolution.js:17609)                              at Object.return (react-dom.development.js:17672)                              at evaluate (alphabetize.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.eastward.              <              computed              >                              [as side by side] (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 information technology! The first 2 lines are all nosotros care about here.

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

Let's decode a couple of these lines:

Here we have:

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

Permit's wait 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 merely I wanted to state information technology explictly: when yous're looking at a stack trace, you lot can near e'er ignore whatever lines that refer to files that are outside your codebase, like ones from a library.

Usually, that ways you'll pay attention to merely the first few lines.

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

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

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

Follow the Clues: How to Diagnose the Mistake

So the stack trace told u.s. where to look: line 9 of App.js. Let'due south open that upward.

Here's the full text of that file:

                          import                                          "./styles.css"              ;              consign                                          default                                          function                                          App              ()                                          {                                          permit                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              Listing of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          fundamental              =              {              particular              .id              }              >                                          {              item              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this 1:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Permit's intermission this down!

  • TypeError is the kind of error

There are a handful 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 property means the lawmaking was trying to read a property.

This is a good inkling! At that place are simply a few means to read backdrop in JavaScript.

The almost common is probably the . operator.

Every bit in user.name, to access the proper name property of the user object.

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

At that place's also brackets (aka foursquare brackets, []) for accessing items in an assortment, like items[5] or items['map'].

You might wonder why the mistake isn't more specific, like "Cannot read function `map` of undefined" – but 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 function. It didn't go that far, considering items is undefined.

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

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

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

Information technology would be way more useful if the fault could say "Cannot read belongings `map` of items". Sadly information technology doesn't say that. It tells you the value of that variable instead.

So now y'all can piece this all together:

  • find the line that the error occurred on (line 9, here)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately earlier the .map and be very suspicious of information technology.

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

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

This defines the variable merely it doesn't prepare it to anything, which means its value is undefined. There'due south the problem. Gear up that, and you set the error!

Fixing This in the Existent World

Of course this case is tiny and contrived, with a simple mistake, and information technology's colocated very close to the site of the mistake. These ones are the easiest to set!

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

Maybe items is a prop passed in from the parent component – and you forgot to pass it downward.

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

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

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

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

You'll become it stock-still! Good luck :)

Success! Now bank check your e-mail.

Learning React can be a struggle — and so many libraries and tools!
My advice? Ignore all of them :)
For a stride-past-stride arroyo, cheque 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 at present

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

Alan Lavender

Alan Lavander

@lavenderlens

metzaccourse.blogspot.com

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

Postar um comentário for "Cannot Read Property 'get' of Undefined at Eval Vue"