Uncaught Typeerror: Cannot Read Property 'local' of Undefined

Got an error like this in your React component?

Cannot read holding `map` of undefined

In this postal service we'll talk most how to fix this one specifically, and along the way you'll larn how to approach fixing errors in full general.

We'll encompass how to read a stack trace, how to interpret the text of the fault, and ultimately how to fix information technology.

The Quick Prepare

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

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

Make certain to initialize the state properly. That ways if it volition eventually be an array, utilise useState([]) instead of something like useState() or useState(null).

Let'southward look at how nosotros tin interpret an mistake message and track downwardly where it happened and why.

How to Find the Mistake

First gild of business is to figure 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

                                                                                                                          six |                                                      return                                      (                                
seven | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> nine | {items . map((particular) => (
| ^
10 | < div cardinal = {detail . id} >
11 | {item . proper noun}
12 | < / div >

Look for the file and the line number offset.

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

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

How to Read the Stack Trace

If yous're looking at the browser console instead, you lot'll demand to read the stack trace to effigy out where the error was.

These always look long and intimidating, simply the play a joke on is that usually yous tin can ignore virtually of it!

The lines are in club of execution, with the virtually recent offset.

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:ix)                                            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.evolution.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.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.render (react-dom.evolution.js:17672)                              at evaluate (alphabetize.js:7)                              at z (eval.js:42)                              at Yard.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.due east.              <              computed              >                              [equally side by side] (runtime.js:97)                              at t (asyncToGenerator.js:three)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore near of it! The starting time 2 lines are all we care about here.

The starting time 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:

Hither we have:

  • App is the proper name of our component function
  • App.js is the file where it appears
  • 9 is the line of that file where the fault occurred

Let's look at some other one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper name of the role where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (information technology's a large file!)

Ignore Files That Aren't Yours

I already mentioned this simply I wanted to country it explictly: when you're looking at a stack trace, you can almost e'er ignore whatever lines that refer to files that are outside your codebase, like ones from a library.

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

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

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

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

Follow the Clues: How to Diagnose the Mistake

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

Here's the full text of that file:

                          import                                          "./styles.css"              ;              consign                                          default                                          role                                          App              ()                                          {                                          let                                          items              ;                                          render                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .proper noun              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this 1:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Allow's break this downward!

  • TypeError is the kind of error

At that place are a handful of born fault types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful part of the fault message)

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

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

The most common is probably the . operator.

As in user.name, to access the name holding of the user object.

Or items.map, to access the map property 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 role `map` of undefined" – but call back, the JS interpreter has no idea what nosotros meant that type to be. It doesn't know it was supposed to be an array, or that map is a part. Information technology didn't get that far, considering items is undefined.

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

This ane is another smashing clue. Combined with the previous bit, you tin be pretty certain you should be looking for .map somewhere on this line.

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

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

And so now y'all tin piece this all together:

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

One time you know which variable to look at, you can read through the role looking for where it comes from, and whether it's initialized.

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

This defines the variable simply it doesn't set up it to anything, which means its value is undefined. At that place's the problem. Set that, and you set up the fault!

Fixing This in the Real World

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

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 lot forgot to pass it down.

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

If information technology'south a local country variable, maybe yous're initializing the state equally undefined – useState(), written like that with no arguments, volition practise exactly this!

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

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

Y'all'll become it fixed! Proficient luck :)

Success! Now cheque your email.

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

Pure React plant

Learn to think in React

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

Start 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 forepart end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

davishossing.blogspot.com

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

0 Response to "Uncaught Typeerror: Cannot Read Property 'local' of Undefined"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel