Grunt Makereport Cannot Read Property Text of Undefined

Got an mistake like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk most how to fix this ane specifically, and along the way you lot'll larn how to approach 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 ready it.

The Quick Fix

This error unremarkably means you're trying to use .map on an assortment, merely that assortment isn't defined yet.

That'due south often because the assortment is a piece of undefined state or an undefined prop.

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

Let'due south await at how we can translate an error message and rails down where it happened and why.

How to Observe the Error

Commencement order of business organisation 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

                                                                                                                          6 |                                                      render                                      (                                
seven | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
x | < div key = {item . id} >
xi | {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 light gray text to a higher place the code block.

btw, when yous encounter 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 wait long and intimidating, but the flim-flam is that usually you can ignore most of it!

The lines are in order of execution, with the most recent get-go.

Here's the stack trace for this error, with the simply of import 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              $i                              (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.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.development.js:14770)                              at updateContainer (react-dom.evolution.js:17211)                              at                            eval                              (react-dom.development.js:17610)                              at unbatchedUpdates (react-dom.evolution.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.render (react-dom.development.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at Yard.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 you could ignore most of information technology! The first 2 lines are all we intendance about here.

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

Allow'southward decode a couple of these lines:

Here we take:

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

Let's await at another ane:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper noun 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 but I wanted to land information technology explictly: when you're looking at a stack trace, you tin nearly 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 down the list until it starts to veer into file names you don't recognize.

In that location are some cases where y'all do care near the full stack, simply they're few and far between, in my experience. Things like… if you doubtable a bug in the library you're using, or if you recall some erroneous input is making its way into library code and bravado up.

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

Follow the Clues: How to Diagnose the Mistake

Then the stack trace told u.s.a. where to await: line 9 of App.js. Let'south open that up.

Here's the full text of that file:

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

Line 9 is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Let's break this down!

  • TypeError is the kind of error

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

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

This is a practiced clue! There are simply a few ways to read properties in JavaScript.

The near mutual is probably the . operator.

Equally in user.name, to access the proper noun property 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'].

Yous might wonder why the mistake isn't more than specific, like "Cannot read office `map` of undefined" – but retrieve, the JS interpreter has no idea what we meant that blazon to be. It doesn't know information technology 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 belongings the lawmaking was trying to read

This 1 is some other great clue. Combined with the previous bit, y'all can be pretty sure you should be looking for .map somewhere on this line.

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

It would be way more than useful if the mistake 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 yous can piece this all together:

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

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

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

This defines the variable but information technology doesn't ready it to anything, which ways its value is undefined. At that place'due south the problem. Ready that, and you lot 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 close to the site of the error. These ones are the easiest to fix!

There 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 laissez passer it down.

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

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

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

Whatsoever the case, though, the process is the same: first where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or use the debugger to audit the intermediate values and figure out why it's undefined.

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

Success! Now check your email.

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

Pure React plant

Acquire to recollect in React

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

Start learning Pure React now

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

daviessatterign.blogspot.com

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

0 Response to "Grunt Makereport Cannot Read Property Text of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel