Upload Error: Typeerror: Cannot Read Property imagename of Undefined

Got an mistake like this in your React component?

Cannot read holding `map` of undefined

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

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

The Quick Fix

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

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

Make sure to initialize the state properly. That means if it will eventually exist an array, use useState([]) instead of something like useState() or useState(null).

Let's await at how nosotros can interpret an error message and rail down where it happened and why.

How to Notice the Error

First lodge of business concern is to figure out where the error is.

If y'all're using Create React App, information technology probably threw upwards a screen like this:

TypeError

Cannot read property 'map' of undefined

App

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

Look for the file and the line number first.

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

btw, when yous see something like /src/App.js:nine:xiii, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If you're looking at the browser panel instead, you'll need to read the stack trace to effigy out where the error was.

These ever wait long and intimidating, only the trick is that usually you can ignore most of it!

The lines are in social club of execution, with the most recent outset.

Here'due south 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.development.js:2804)                              at beginWork              $ane                              (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.development.js:17609)                              at Object.return (react-dom.development.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at Grand.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.due east.              <              computed              >                              [as next] (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 first 2 lines are all nosotros care about here.

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

Let's decode a couple of these lines:

Hither we take:

  • 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

Allow'due south look at another one:

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

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

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

In that location are some cases where you practise care near the full stack, only they're few and far between, in my experience. Things like… if you lot suspect a problems in the library you'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 issues volition exist in your own code ;)

Follow the Clues: How to Diagnose the Error

So the stack trace told united states of america where to wait: line 9 of App.js. Let's open that upward.

Here'southward the full text of that file:

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

Line 9 is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let's interruption this downwards!

  • TypeError is the kind of error

At that place are a handful of congenital-in mistake 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 error message)

  • Cannot read property means the lawmaking was trying to read a holding.

This is a good inkling! There are simply 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 belongings of the items object.

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

You might wonder why the fault isn't more specific, like "Cannot read role `map` of undefined" – but think, the JS interpreter has no idea what nosotros meant that blazon to exist. It doesn't know it was supposed to be an assortment, or that map is a function. Information technology didn't get that far, considering items is undefined.

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

This one is another smashing inkling. Combined with the previous bit, you can be pretty sure you should be looking for .map somewhere on this line.

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

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

And so at present you tin can slice this all together:

  • discover the line that the fault 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 it.

In one case you know which variable to expect at, you can read through the function looking for where it comes from, and whether it's initialized.

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

This defines the variable but it doesn't prepare it to anything, which means its value is undefined. There'southward the problem. Fix that, and you fix the mistake!

Fixing This in the Real World

Of course this example is tiny and contrived, with a simple mistake, and information technology's colocated very close to the site of the error. 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 you did pass that prop, simply the value being passed in is actually undefined or null.

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

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

Any the example, though, the procedure is the same: beginning where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouth or utilize the debugger to audit the intermediate values and figure out why it'southward undefined.

You'll become it fixed! Proficient luck :)

Success! At present check your email.

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

Pure React plant

Learn to call back in React

  • 90+ screencast lessons
  • Full transcripts and closed captions
  • All the code from the lessons
  • Programmer interviews

Beginning learning Pure React now

Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'grand 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

howardbearbing.blogspot.com

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

0 Response to "Upload Error: Typeerror: Cannot Read Property imagename of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel