Skip to content Skip to sidebar Skip to footer

Cannot Read Property 'value' of Undefined React

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to fix this 1 specifically, and along the mode y'all'll learn how to approach 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 prepare it.

The Quick Fix

This error commonly means y'all're trying to apply .map on an assortment, merely that assortment isn't defined yet.

That's oftentimes because the array is a piece of undefined country or an undefined prop.

Brand sure to initialize the state properly. That means if it will eventually be an assortment, utilise useState([]) instead of something like useState() or useState(goose egg).

Let's look at how we tin translate an mistake message and track down where it happened and why.

How to Find the Fault

First order of business organisation is to figure out where the mistake is.

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

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
seven | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> nine | {items . map((item) => (
| ^
ten | < div key = {item . id} >
11 | {item . name}
12 | < / div >

Wait for the file and the line number first.

Here, that's /src/App.js and line 9, taken from the low-cal gray 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 console instead, you lot'll need to read the stack trace to figure out where the error was.

These ever look long and intimidating, only the play tricks is that usually you lot tin ignore virtually of it!

The lines are in order of execution, with the nearly recent first.

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

                                          TypeError: Cannot                                read                                  property                                'map'                                  of undefined                                                              at App (App.js:9)                                            at renderWithHooks (react-dom.development.js:10021)                              at mountIndeterminateComponent (react-dom.evolution.js:12143)                              at beginWork (react-dom.evolution.js:12942)                              at HTMLUnknownElement.callCallback (react-dom.evolution.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.development.js:15339)                              at workLoopSync (react-dom.development.js:15293)                              at renderRootSync (react-dom.development.js:15268)                              at performSyncWorkOnRoot (react-dom.evolution.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.development.js:15104)                              at legacyRenderSubtreeIntoContainer (react-dom.evolution.js:17609)                              at Object.return (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 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              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you lot could ignore nigh of it! The outset 2 lines are all we care well-nigh hither.

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

Permit's decode a couple of these lines:

Here we have:

  • 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's expect at another one:

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

Ignore Files That Aren't Yours

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

Normally, that means you lot'll pay attending to merely 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 you do care nigh the full stack, but they're few and far betwixt, in my feel. Things similar… if you lot suspect a bug in the library you're using, or if yous think some erroneous input is making its mode into library lawmaking and bravado up.

The vast majority of the time, though, the bug volition be in your own code ;)

Follow the Clues: How to Diagnose the Error

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

Here's the total text of that file:

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

Line 9 is this i:

And but for reference, here'southward that fault bulletin once again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'southward break this down!

  • TypeError is the kind of error

There are a handful of born error types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid blazon." (this function is, IMO, the to the lowest degree useful function of the fault bulletin)

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

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

The near mutual is probably the . operator.

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

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

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

You lot might wonder why the error isn't more specific, like "Cannot read role `map` of undefined" – just recall, the JS interpreter has no idea what we meant that type to be. Information technology doesn't know information technology was supposed to be an array, or that map is a function. It didn't get that far, because items is undefined.

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

This one is some other corking clue. Combined with the previous bit, you can be pretty certain yous should exist looking for .map somewhere on this line.

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

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

So now you can piece this all together:

  • find the line that the mistake occurred on (line 9, here)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately earlier the .map and exist very suspicious of it.

Once you lot know which variable to look at, you can read through the role looking for where it comes from, and whether it'due south 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. There's the problem. Prepare that, and yous prepare the error!

Fixing This in the Existent Earth

Of course this instance is tiny and contrived, with a simple mistake, and it'south colocated very shut to the site of the error. These ones are the easiest to set up!

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

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

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

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

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

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

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

Success! Now bank check your email.

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

Pure React plant

Learn to think in React

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

Outset learning Pure React now

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

Alan Lavender

Alan Lavander

@lavenderlens

leeboxistaken.blogspot.com

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

Post a Comment for "Cannot Read Property 'value' of Undefined React"