Wednesday, March 22, 2023
HomeReactHow one can Learn React Errors (repair 'Can't learn property of undefined'!)

How one can Learn React Errors (repair ‘Can’t learn property of undefined’!)

Bought an error like this in your React element?

Can’t learn property `map` of undefined

On this publish we’ll speak about the right way to repair this one particularly, and alongside the best way you’ll learn to method fixing errors generally.

We’ll cowl the right way to learn a stack hint, the right way to interpret the textual content of the error, and finally the right way to repair it.

The Fast Repair

This error often means you’re attempting to make use of .map on an array, however that array isn’t outlined but.

That’s actually because the array is a bit of undefined state or an undefined prop.

Be sure that to initialize the state correctly. Which means if it’ll finally be an array, use useState([]) as an alternative of one thing like useState() or useState(null).

Let’s have a look at how we are able to interpret an error message and observe down the place it occurred and why.

How one can Discover the Error

First order of enterprise is to determine the place the error is.

In case you’re utilizing Create React App, it most likely threw up a display like this:


Can’t learn property ‘map’ of undefined


   6 | return (
7 | <div className="App">
8 | <h1>Listing of Objects</h1>
> 9 | { => (
| ^
10 | <div key={}>
11 | {merchandise.title}
12 | </div>

Search for the file and the line quantity first.

Right here, that’s /src/App.js and line 9, taken from the sunshine grey textual content above the code block.

btw, once you see one thing like /src/App.js:9:13, the best way to decode that’s filename:lineNumber:columnNumber.

How one can Learn the Stack Hint

In case you’re wanting on the browser console as an alternative, you’ll have to learn the stack hint to determine the place the error was.

These all the time look lengthy and intimidating, however the trick is that often you possibly can ignore most of it!

The strains are so as of execution, with the latest first.

Right here’s the stack hint for this error, with the one essential strains highlighted:

TypeError: Can't learn property 'map' of undefined
    at App (App.js:9)
    at renderWithHooks (react-dom.growth.js:10021)
    at mountIndeterminateComponent (react-dom.growth.js:12143)
    at beginWork (react-dom.growth.js:12942)
    at HTMLUnknownElement.callCallback (react-dom.growth.js:2746)
    at Object.invokeGuardedCallbackDev (react-dom.growth.js:2770)
    at invokeGuardedCallback (react-dom.growth.js:2804)
    at beginWork$1 (react-dom.growth.js:16114)
    at performUnitOfWork (react-dom.growth.js:15339)
    at workLoopSync (react-dom.growth.js:15293)
    at renderRootSync (react-dom.growth.js:15268)
    at performSyncWorkOnRoot (react-dom.growth.js:15008)
    at scheduleUpdateOnFiber (react-dom.growth.js:14770)
    at updateContainer (react-dom.growth.js:17211)
    at eval (react-dom.growth.js:17610)
    at unbatchedUpdates (react-dom.growth.js:15104)
    at legacyRenderSubtreeIntoContainer (react-dom.growth.js:17609)
    at Object.render (react-dom.growth.js:17672)
    at consider (index.js:7)
    at z (eval.js:42)
    at G.consider (transpiled-module.js:692)
    at be.evaluateTranspiledModule (supervisor.js:286)
    at be.evaluateModule (supervisor.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 once I stated you might ignore most of it! The primary 2 strains are all we care about right here.

The primary line is the error message, and each line after that spells out the unwound stack of perform calls that led to it.

Let’s decode a few these strains:

Right here we have now:

  • App is the title of our element perform
  • App.js is the file the place it seems
  • 9 is the road of that file the place the error occurred

Let’s have a look at one other one:

at performSyncWorkOnRoot (react-dom.growth.js:15008)
  • performSyncWorkOnRoot is the title of the perform the place this occurred
  • react-dom.growth.js is the file
  • 15008 is the road quantity (it’s an enormous file!)

Ignore Information That Aren’t Yours

I already talked about this however I wished to state it explictly: once you’re taking a look at a stack hint, you possibly can virtually all the time ignore any strains that consult with recordsdata which can be exterior your codebase, like ones from a library.

Normally, which means you’ll take note of solely the primary few strains.

Scan down the record till it begins to veer into file names you don’t acknowledge.

There are some circumstances the place you do care in regards to the full stack, however they’re few and much between, in my expertise. Issues like… should you suspect a bug within the library you’re utilizing, or should you suppose some inaccurate enter is making its means into library code and blowing up.

The overwhelming majority of the time, although, the bug might be in your individual code 😉

Comply with the Clues: How one can Diagnose the Error

So the stack hint instructed us the place to look: line 9 of App.js. Let’s open that up.

Right here’s the total textual content of that file:

import "./kinds.css";

export default perform App() {
  let gadgets;

  return (
    <div className="App">
      <h1>Listing of Objects</h1>
      { => (
        <div key={}>

Line 9 is that this one:

And only for reference, right here’s that error message once more:

TypeError: Can't learn property 'map' of undefined

Let’s break this down!

  • TypeError is the type of error

There are a handful of built-in error varieties. MDN says TypeError “represents an error that happens when a variable or parameter will not be of a legitimate kind.” (this half is, IMO, the least helpful a part of the error message)

  • Can't learn property means the code was attempting to learn a property.

This can be a good clue! There are just a few methods to learn properties in JavaScript.

The most typical might be the . operator.

As in person.title, to entry the title property of the person object.

Or, to entry the map property of the gadgets object.

There’s additionally brackets (aka sq. brackets, []) for accessing gadgets in an array, like gadgets[5] or gadgets['map'].

You would possibly surprise why the error isn’t extra particular, like “Can’t learn perform `map` of undefined” – however bear in mind, the JS interpreter has no thought what we meant that kind to be. It doesn’t understand it was presupposed to be an array, or that map is a perform. It didn’t get that far, as a result of gadgets is undefined.

  • 'map' is the property the code was attempting to learn

This one is one other nice clue. Mixed with the earlier bit, you might be fairly certain you ought to be on the lookout for .map someplace on this line.

  • of undefined is a clue in regards to the worth of the variable

It will be far more helpful if the error might say “Can’t learn property `map` of things”. Sadly it doesn’t say that. It tells you the worth of that variable as an alternative.

So now you possibly can piece this all collectively:

  • discover the road that the error occurred on (line 9, right here)
  • scan that line on the lookout for .map
  • have a look at the variable/expression/no matter instantly earlier than the .map and be very suspicious of it.

As soon as you already know which variable to take a look at, you possibly can learn by means of the perform on the lookout for the place it comes from, and whether or not it’s initialized.

In our little instance, the one different incidence of gadgets is line 4:

This defines the variable nevertheless it doesn’t set it to something, which suggests its worth is undefined. There’s the issue. Repair that, and also you repair the error!

Fixing This within the Actual World

After all this instance is tiny and contrived, with a easy mistake, and it’s colocated very near the positioning of the error. These ones are the best to repair!

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

Perhaps gadgets is a prop handed in from the dad or mum element – and also you forgot to cross it down.

Or perhaps you did cross that prop, however the worth being handed in is definitely undefined or null.

If it’s an area state variable, perhaps you’re initializing the state as undefined – useState(), written like that with no arguments, will do precisely this!

If it’s a prop coming from Redux, perhaps your mapStateToProps is lacking the worth, or has a typo.

Regardless of the case, although, the method is identical: begin the place the error is and work backwards, verifying your assumptions at every level the variable is used. Throw in some console.logs or use the debugger to examine the intermediate values and work out why it’s undefined.

You’ll get it mounted! Good luck 🙂

Success! Now test your e-mail.

Studying React generally is a wrestle — so many libraries and instruments!
My recommendation? Ignore all of them 🙂
For a step-by-step method, try my Pure React workshop.

Pure React plant

Be taught to suppose in React

  • 90+ screencast classes
  • Full transcripts and closed captions
  • All of the code from the teachings
  • Developer interviews

Begin studying Pure React now

Dave Ceddia’s Pure React is a piece of monumental readability and depth. Hats off. I am a React coach in London and would totally advocate this to all entrance finish devs desirous to upskill or consolidate.

Alan Lavender

Alan Lavender




Please enter your comment!
Please enter your name here

Most Popular

Recent Comments