Typeerror: Cannot Read Property 'locked' of Undefined Select2

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to ready this one specifically, and along the way you'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 fault, and ultimately how to fix it.

The Quick Ready

This mistake usually ways you lot're trying to use .map on an array, simply that array isn't defined yet.

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

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

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

How to Notice the Mistake

Get-go social club of business is to figure out where the fault is.

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

TypeError

Cannot read property 'map' of undefined

App

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

Look for the file and the line number get-go.

Here, that'due south /src/App.js and line 9, taken from the lite gray text in a higher place the code cake.

btw, when you lot 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, you lot'll demand to read the stack trace to figure out where the error was.

These always wait long and intimidating, but the trick is that ordinarily you tin can ignore most of it!

The lines are in order of execution, with the virtually recent first.

Here'due south 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.evolution.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.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.development.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (alphabetize.js:7)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at exist.evaluateTranspiledModule (director.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:iii)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore nearly of information technology! The first 2 lines are all nosotros care about hither.

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

Let'due south decode a couple of these lines:

Here nosotros accept:

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

Let's look at another one:

                          at performSyncWorkOnRoot (react-dom.evolution.js:15008)                                    
  • performSyncWorkOnRoot is the proper name of the function 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 just I wanted to country information technology explictly: when you lot're looking at a stack trace, you tin can nearly always ignore any lines that refer to files that are exterior your codebase, like ones from a library.

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

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

There are some cases where you do care nigh the total stack, merely they're few and far between, in my experience. Things similar… if y'all suspect a bug in the library you're using, or if you lot think some erroneous input is making its manner into library code and blowing up.

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

Follow the Clues: How to Diagnose the Error

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

Here's the full text of that file:

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

Line ix is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let'due south break this downwards!

  • TypeError is the kind of error

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

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

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

The most common is probably the . operator.

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

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

In that location's too brackets (aka square brackets, []) for accessing items in an assortment, similar items[5] or items['map'].

You might wonder why the fault isn't more specific, like "Cannot read office `map` of undefined" – just remember, the JS interpreter has no idea what nosotros meant that type to be. It doesn't know it was supposed to be an assortment, or that map is a function. Information technology didn't become that far, because items is undefined.

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

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

  • of undefined is a clue well-nigh 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 y'all the value of that variable instead.

So now you can piece this all together:

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

In one case y'all know which variable to look at, yous can read through the function looking for where information technology comes from, and whether it's initialized.

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

This defines the variable merely it doesn't set it to annihilation, which ways its value is undefined. There's the problem. Ready that, and you set up the error!

Fixing This in the Existent World

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

At that place 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 down.

Or maybe yous did pass that prop, but the value existence passed in is actually undefined or nil.

If it's a local state variable, maybe y'all're initializing the state as undefined – useState(), written like that with no arguments, volition do exactly this!

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

Whatever the case, though, the procedure is the aforementioned: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and effigy out why it's undefined.

Y'all'll get it fixed! Good luck :)

Success! Now check your email.

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

Pure React plant

Acquire to recall in React

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

Start learning Pure React now

Dave Ceddia'south 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

donleyhobbiregrato.blogspot.com

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

0 Response to "Typeerror: Cannot Read Property 'locked' of Undefined Select2"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel