Typeerror: Cannot Read Property 'setcontent' of Undefined

Got an error like this in your React component?

Cannot read holding `map` of undefined

In this post we'll talk near how to gear up this i specifically, and along the way you'll acquire how to arroyo fixing errors in general.

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

The Quick Gear up

This error usually ways you're trying to utilise .map on an array, but that array isn't defined yet.

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

Make certain to initialize the country properly. That means if it will eventually be an assortment, use useState([]) instead of something like useState() or useState(nil).

Permit's expect at how we can interpret an fault bulletin and rail down where it happened and why.

How to Notice the Mistake

First order of business is to effigy out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

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

Look for the file and the line number first.

Here, that'due south /src/App.js and line 9, taken from the light grayness text above the code block.

btw, when y'all encounter something similar /src/App.js:ix:thirteen, the manner to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

These always look long and intimidating, just the trick is that normally yous tin can ignore most of it!

The lines are in order of execution, with the almost recent showtime.

Hither'southward the stack trace for this error, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  property                                '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.evolution.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:7)                              at z (eval.js:42)                              at Thousand.evaluate (transpiled-module.js:692)                              at exist.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              >                              [equally 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 offset ii lines are all we care about here.

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

Allow'due south decode a couple of these lines:

Hither we accept:

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

Allow's look at another one:

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

Ignore Files That Aren't Yours

I already mentioned this but I wanted to state it explictly: when yous're looking at a stack trace, you can almost ever ignore any lines that refer to files that are outside your codebase, like ones from a library.

Ordinarily, that means you'll pay attending to merely the first few lines.

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

There are some cases where you do care nearly the full stack, but they're few and far between, in my feel. Things like… if you suspect a bug in the library you're using, or if you call up some erroneous input is making its manner into library code and blowing upwards.

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

Follow the Clues: How to Diagnose the Fault

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

Here's the total text of that file:

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

Line ix is this one:

And just for reference, here'southward that error message once more:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'southward break this down!

  • TypeError is the kind of error

There are a handful of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this function is, IMO, the least useful function of the fault message)

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

This is a good clue! In that location are but a few ways to read properties in JavaScript.

The near common is probably the . operator.

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

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

There'southward also brackets (aka square brackets, []) for accessing items in an assortment, like items[v] or items['map'].

You might wonder why the error isn't more than specific, like "Cannot read office `map` of undefined" – but remember, the JS interpreter has no thought what nosotros meant that type to be. It doesn't know it was supposed to exist an assortment, or that map is a role. It didn't get that far, because items is undefined.

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

This 1 is another neat clue. Combined with the previous chip, you lot tin can be pretty sure you should exist looking for .map somewhere on this line.

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

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

And then now you tin can slice this all together:

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

Once you know which variable to await at, you tin read through the office looking for where it comes from, and whether it's initialized.

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

This defines the variable merely information technology doesn't ready it to anything, which means its value is undefined. There'southward the problem. Fix that, and you fix the error!

Fixing This in the Real Earth

Of course this example is tiny and contrived, with a uncomplicated mistake, and it's colocated very shut to the site of the mistake. These ones are the easiest to set!

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 y'all forgot to laissez passer it down.

Or possibly you did pass that prop, only the value existence passed in is really undefined or null.

If it's a local state variable, perhaps y'all're initializing the state as undefined – useState(), written like that with no arguments, volition 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 instance, though, the process is the same: first where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or employ the debugger to inspect the intermediate values and figure out why it's undefined.

Yous'll become information technology fixed! Expert luck :)

Success! At present check your e-mail.

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

Pure React plant

Learn to recollect 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's Pure React is a work of enormous clarity and depth. Hats off. I'thou a React trainer in London and would thoroughly recommend this to all front stop devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

peekpandeo.blogspot.com

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

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

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel