Uncaught Typeerror: Cannot Read Property 'slidestoshow' of Undefined

Got an error similar this in your React component?

Cannot read holding `map` of undefined

In this mail we'll talk about how to fix this ane specifically, and along the style you'll larn how to approach fixing errors in full general.

We'll cover how to read a stack trace, how to interpret the text of the error, and ultimately how to prepare it.

The Quick Gear up

This fault unremarkably ways you're trying to apply .map on an assortment, only that array isn't defined yet.

That's oftentimes 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 eventually be an array, use useState([]) instead of something like useState() or useState(null).

Let'southward look at how nosotros tin interpret an error bulletin and track down where it happened and why.

How to Find the Error

Outset order of business concern is to effigy out where the fault is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          vi |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((particular) => (
| ^
10 | < div key = {detail . id} >
11 | {item . name}
12 | < / div >

Look for the file and the line number showtime.

Hither, that's /src/App.js and line ix, taken from the light gray text to a higher place the code block.

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

These ever expect long and intimidating, but the trick is that normally you lot tin can ignore well-nigh of information technology!

The lines are in order of execution, with the well-nigh recent outset.

Hither's the stack trace for this mistake, with the only 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.evolution.js:2804)                              at beginWork              $1                              (react-dom.development.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.development.js:17610)                              at unbatchedUpdates (react-dom.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.development.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:vii)                              at z (eval.js:42)                              at One thousand.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 adjacent] (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 start 2 lines are all we care about here.

The beginning line is the error message, and every line later on that spells out the unwound stack of office calls that led to it.

Let'south 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
  • 9 is the line of that file where the error occurred

Let's look at some other ane:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the 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 but I wanted to land it explictly: when you're looking at a stack trace, you can nigh always ignore any lines that refer to files that are exterior your codebase, like ones from a library.

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

Browse down the list until it starts to veer into file names y'all don't recognize.

In that location are some cases where you do intendance nearly the total stack, simply they're few and far between, in my feel. Things like… if y'all doubtable a bug in the library yous're using, or if y'all retrieve some erroneous input is making its mode into library code and blowing upwardly.

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

Follow the Clues: How to Diagnose the Error

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

Hither'southward the full text of that file:

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

Line ix is this ane:

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

                          TypeError: Cannot read belongings 'map' of undefined                                    

Allow's suspension this down!

  • TypeError is the kind of fault

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 type." (this role is, IMO, the least useful role of the fault message)

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

This is a good inkling! There are only a few means to read backdrop in JavaScript.

The most common is probably the . operator.

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

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

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

You might wonder why the error isn't more than specific, like "Cannot read function `map` of undefined" – but call up, the JS interpreter has no idea what we meant that blazon 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 property the code was trying to read

This one is another cracking clue. Combined with the previous flake, you can be pretty sure y'all should be looking for .map somewhere on this line.

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

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

Then at present you can piece this all together:

  • find the line that the error occurred on (line 9, hither)
  • scan that line looking for .map
  • await at the variable/expression/whatever immediately before the .map and exist very suspicious of information technology.

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

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

This defines the variable but information technology doesn't set up it to anything, which means its value is undefined. In that location's the trouble. Fix that, and yous fix the fault!

Fixing This in the Real Earth

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

At that place are a ton of potential causes for an error similar this, though.

Peradventure items is a prop passed in from the parent component – and y'all forgot to pass it downwards.

Or mayhap you did pass that prop, merely the value existence passed in is actually undefined or zippo.

If it's a local country variable, perhaps yous're initializing the country every bit undefined – useState(), written like that with no arguments, will do exactly this!

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

Whatever the case, though, the process is the same: start where the mistake 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 figure out why it's undefined.

You lot'll get it fixed! Good luck :)

Success! Now check your email.

Learning React can be a struggle — then many libraries and tools!
My advice? Ignore all of them :)
For a pace-by-step arroyo, check out my Pure React workshop.

Pure React plant

Acquire to retrieve in React

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

Get-go learning Pure React at present

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

Alan Lavender

Alan Lavander

@lavenderlens

nisbetorpon1948.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel