Create React App Typeerror: Cannot Read Property 'get' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk about how to set this i specifically, and along the way you'll learn how to arroyo fixing errors in general.

We'll cover how to read a stack trace, how to interpret the text of the error, and ultimately how to fix information technology.

The Quick Prepare

This mistake unremarkably means you lot're trying to employ .map on an array, just that array isn't divers all the same.

That's often because the array is a slice of undefined state 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(zip).

Let'due south look at how we tin interpret an error message and track downward where it happened and why.

How to Detect the Mistake

First society of business is to figure out where the error is.

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

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      render                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> 9 | {items . map((detail) => (
| ^
10 | < div key = {particular . id} >
11 | {particular . name}
12 | < / div >

Look for the file and the line number beginning.

Here, that's /src/App.js and line ix, taken from the light gray text in a higher place the lawmaking cake.

btw, when you lot run across something similar /src/App.js:9:13, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

These ever await long and intimidating, but the fob is that commonly you tin ignore most of it!

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

Hither'south the stack trace for this mistake, with the simply important lines highlighted:

                                          TypeError: Cannot                                read                                  holding                                'map'                                  of undefined                                                              at App (App.js:ix)                                            at renderWithHooks (react-dom.development.js:10021)                              at mountIndeterminateComponent (react-dom.evolution.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              $1                              (react-dom.evolution.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.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:7)                              at z (eval.js:42)                              at G.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at be.evaluateModule (managing director.js:257)                              at compile.ts:717                              at 50 (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              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 information technology! The first 2 lines are all we care nearly hither.

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

Let's decode a couple of these lines:

Hither we have:

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

Let's wait at another ane:

                          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 (it'southward a big file!)

Ignore Files That Aren't Yours

I already mentioned this but I wanted to state it explictly: when you lot're looking at a stack trace, y'all can most always ignore any lines that refer to files that are exterior your codebase, similar ones from a library.

Usually, that ways you'll pay attention to only the outset few lines.

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

There are some cases where yous do care almost the full stack, but they're few and far between, in my experience. Things similar… if you suspect a problems in the library you're using, or if you think some erroneous input is making its mode into library code and blowing upward.

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

Follow the Clues: How to Diagnose the Error

So the stack trace told us where to look: line ix of App.js. Permit's open that up.

Here's the full text of that file:

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

Line nine is this one:

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

                          TypeError: Cannot read property 'map' of undefined                                    

Permit's break this down!

  • TypeError is the kind of mistake

At that place are a handful of built-in error 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 bulletin)

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

This is a good clue! There are only a few ways to read properties in JavaScript.

The most common is probably the . operator.

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

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

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

Y'all might wonder why the error isn't more specific, like "Cannot read function `map` of undefined" – but remember, the JS interpreter has no thought what we meant that type to be. It doesn't know it was supposed to exist an array, or that map is a part. It didn't become that far, because items is undefined.

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

This one is another great clue. Combined with the previous flake, you can be pretty sure you lot should be looking for .map somewhere on this line.

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

It would exist way 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.

So now you tin piece this all together:

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

Once you lot know which variable to look at, you can 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 four:

This defines the variable but it doesn't set it to anything, which ways its value is undefined. There's the trouble. Set that, and you ready the error!

Fixing This in the Real World

Of course this case is tiny and contrived, with a simple mistake, and information technology'southward colocated very close to the site of the error. These ones are the easiest to prepare!

There are a ton of potential causes for an error like this, though.

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

Or peradventure yous did laissez passer that prop, merely the value being passed in is actually undefined or null.

If it's a local state variable, maybe you're initializing the state as undefined – useState(), written like that with no arguments, volition practise exactly this!

If it's 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: start where the mistake is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouth or use the debugger to inspect the intermediate values and figure out why it's undefined.

You lot'll get information technology fixed! Good luck :)

Success! Now check your email.

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

Pure React plant

Learn to remember in React

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

First learning Pure React at present

Dave Ceddia's 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 front end terminate devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

millerpell1974.blogspot.com

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

0 Response to "Create React App Typeerror: Cannot Read Property 'get' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel