Browserify Bundle.js Uncaught Typeerror: Cannot Read Property 'prototype' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk nearly how to fix this one specifically, and forth the way you'll learn how to approach fixing errors in general.

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

The Quick Fix

This error usually ways y'all're trying to use .map on an array, but that assortment isn't defined yet.

That'south ofttimes because the array is a piece of undefined country or an undefined prop.

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

Let'due south look at how nosotros can interpret an error message and track down where information technology happened and why.

How to Find the Error

Get-go gild of business concern 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 > Listing of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div key = {item . id} >
xi | {particular . name}
12 | < / div >

Wait for the file and the line number first.

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

btw, when you see something like /src/App.js:nine: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'll need to read the stack trace to figure out where the error was.

These always look long and intimidating, merely the fox is that normally y'all tin can ignore almost of it!

The lines are in gild of execution, with the most recent first.

Here's the stack trace for this error, with the only of import 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.development.js:12143)                              at beginWork (react-dom.development.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.evolution.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $1                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.evolution.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.development.js:15268)                              at performSyncWorkOnRoot (react-dom.evolution.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.render (react-dom.evolution.js:17672)                              at evaluate (index.js:vii)                              at z (eval.js:42)                              at K.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.east.              <              computed              >                              [every bit next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said y'all could ignore well-nigh of it! The starting time two lines are all we care about here.

The first line is the fault bulletin, and every line after that spells out the unwound stack of function calls that led to it.

Permit'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 error occurred

Let's look at another one:

                          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 (information technology's a big file!)

Ignore Files That Aren't Yours

I already mentioned this merely I wanted to state information technology explictly: when you're looking at a stack trace, y'all can almost always ignore whatsoever lines that refer to files that are exterior your codebase, like ones from a library.

Unremarkably, that means you'll pay attending to only the first few lines.

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

There are some cases where yous do intendance about the full stack, merely they're few and far between, in my experience. Things similar… if you doubtable a bug in the library you're using, or if you recollect some erroneous input is making its way into library code and blowing upwardly.

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

Follow the Clues: How to Diagnose the Error

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

Hither's the full text of that file:

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

Line 9 is this 1:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let'south interruption this down!

  • TypeError is the kind of error

There are a handful of built-in mistake 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 least useful function of the error message)

  • Cannot read holding ways the code was trying to read a belongings.

This is a good clue! There are merely a few ways to read backdrop in JavaScript.

The nigh common is probably the . operator.

As in user.name, to access the proper name property 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, like items[five] or items['map'].

You might wonder why the mistake isn't more than specific, like "Cannot read function `map` of undefined" – but remember, the JS interpreter has no idea what nosotros meant that blazon to be. It doesn't know it was supposed to exist an array, 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 i is another great inkling. Combined with the previous bit, you tin can be pretty certain you should exist looking for .map somewhere on this line.

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

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

So now you can piece this all together:

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

One time you know which variable to wait at, you lot can read through the function looking for where information technology comes from, and whether it'due south initialized.

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

This defines the variable but information technology doesn't set it to annihilation, which means its value is undefined. There's the problem. Fix that, and you lot fix the error!

Fixing This in the Real Globe

Of form this example is tiny and contrived, with a unproblematic error, and it'southward colocated very close to the site of the fault. These ones are the easiest to fix!

In that location are a ton of potential causes for an fault 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 pass that prop, just the value being passed in is actually undefined or null.

If it's a local state variable, mayhap you lot're initializing the state as undefined – useState(), written similar that with no arguments, will do exactly this!

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

Whatsoever the example, though, the process is the same: start where the error is and work backwards, verifying your assumptions at each betoken the variable is used. Throw in some console.logs or employ the debugger to inspect the intermediate values and figure out why it'southward undefined.

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

Success! Now check your e-mail.

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

Pure React plant

Learn to think in React

  • 90+ screencast lessons
  • Total transcripts and closed captions
  • All the lawmaking 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'yard a React trainer in London and would thoroughly recommend this to all front end cease devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

peakepashe1989.blogspot.com

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

0 Response to "Browserify Bundle.js Uncaught Typeerror: Cannot Read Property 'prototype' of Undefined"

Kommentar veröffentlichen

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel