Uncaught Typeerror: Cannot Read Property 'setstate' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this mail we'll talk most how to set this one specifically, and along the way you'll acquire how to approach fixing errors in full general.

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

The Quick Gear up

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

That'due south ofttimes considering the array is a slice of undefined state or an undefined prop.

Make 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).

Allow's look at how we can translate an mistake message and track downwardly where it happened and why.

How to Find the Error

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

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

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          vi |                                                      return                                      (                                
7 | < div className = "App" >
eight | < h1 > List of Items < / h1 >
> 9 | {items . map((detail) => (
| ^
x | < div fundamental = {item . 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 gray text above the lawmaking block.

btw, when you meet something like /src/App.js:nine:thirteen, the manner 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 figure out where the error was.

These always look long and intimidating, but the trick is that usually you tin can ignore near of it!

The lines are in club of execution, with the most contempo first.

Here's the stack trace for this error, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                'map'                                  of undefined                                                              at App (App.js:9)                                            at renderWithHooks (react-dom.evolution.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.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.development.js:15293)                              at renderRootSync (react-dom.evolution.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.evolution.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:seven)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (director.js:286)                              at be.evaluateModule (managing director.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.east.              <              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 well-nigh of it! The first ii lines are all we care about hither.

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

Permit'south decode a couple of these lines:

Here we have:

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

Let's await at some other 1:

                          at performSyncWorkOnRoot (react-dom.evolution.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'south a large file!)

Ignore Files That Aren't Yours

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

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

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

There are some cases where you do care about the total stack, but they're few and far between, in my feel. Things similar… if you doubtable a bug in the library you're using, or if you think some erroneous input is making its mode into library code and blowing up.

The vast bulk of the fourth dimension, though, the bug volition exist in your ain code ;)

Follow the Clues: How to Diagnose the Mistake

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

Hither's the full text of that file:

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

Line 9 is this 1:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let's suspension this down!

  • TypeError is the kind of error

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

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

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

The nearly common is probably the . operator.

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

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

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

You might wonder why the error isn't more specific, similar "Cannot read role `map` of undefined" – but call back, the JS interpreter has no thought what nosotros meant that blazon to be. It doesn't know it was supposed to be an array, or that map is a office. Information technology didn't get that far, because items is undefined.

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

This 1 is another dandy inkling. Combined with the previous bit, you lot can be pretty certain you should be looking for .map somewhere on this line.

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

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

So now you can piece this all together:

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

Once y'all know which variable to look at, y'all 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 4:

This defines the variable but it doesn't set it to anything, which means its value is undefined. In that location's the problem. Gear up that, and yous fix the error!

Fixing This in the Existent Globe

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

In that location are a ton of potential causes for an fault like this, though.

Maybe items is a prop passed in from the parent component – and you forgot to pass it down.

Or perhaps you did pass that prop, but the value being passed in is actually undefined or naught.

If information technology's a local state variable, maybe you're initializing the land as undefined – useState(), written like 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 procedure is the same: 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 figure out why information technology's undefined.

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

Success! Now 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-footstep approach, check out my Pure React workshop.

Pure React plant

Learn to call back in React

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

Kickoff learning Pure React at present

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

Alan Lavender

Alan Lavender

@lavenderlens

jacquesthersemeaten.blogspot.com

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

Belum ada Komentar untuk "Uncaught Typeerror: Cannot Read Property 'setstate' of Undefined"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel