Cannot Read Property \'filename\' of Undefined Salesforce

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this post nosotros'll talk about how to fix this one specifically, and along the way you'll acquire how to approach fixing errors in general.

We'll embrace how to read a stack trace, how to translate the text of the error, and ultimately how to set up it.

The Quick Gear up

This mistake ordinarily means you're trying to use .map on an array, but that array isn't divers withal.

That'southward ofttimes considering the array is a slice of undefined land or an undefined prop.

Brand sure to initialize the state properly. That means if information technology will eventually be an array, use useState([]) instead of something like useState() or useState(nada).

Let's look at how we can interpret an error bulletin and track down where it happened and why.

How to Find the Mistake

First social club 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

                                                                                                                          half dozen |                                                      return                                      (                                
7 | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((particular) => (
| ^
10 | < div cardinal = {item . id} >
11 | {item . name}
12 | < / div >

Expect 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 lawmaking block.

btw, when you run into something like /src/App.js:nine:13, the fashion to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

If yous're looking at the browser console instead, yous'll need to read the stack trace to effigy out where the error was.

These e'er look long and intimidating, but the play a trick on is that ordinarily you can ignore virtually of it!

The lines are in club of execution, with the most recent offset.

Hither's the stack trace for this error, with the merely important lines highlighted:

                                          TypeError: Cannot                                read                                  belongings                                '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.evolution.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $1                              (react-dom.development.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.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.evolution.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 (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.eastward.              <              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 about of it! The first ii lines are all we care well-nigh here.

The first line is the error bulletin, and every line later 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 mistake occurred

Let's look at some other one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the office where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it's a big 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 almost e'er ignore any lines that refer to files that are outside your codebase, like ones from a library.

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

Scan down the listing until it starts to veer into file names you lot don't recognize.

There are some cases where y'all practice intendance about the full stack, but they're few and far between, in my experience. Things similar… if you suspect a issues in the library yous're using, or if you think some erroneous input is making its way into library lawmaking and blowing up.

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

Follow the Clues: How to Diagnose the Fault

And then the stack trace told us where to expect: line 9 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              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              item              .id              }              >                                          {              item              .proper name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line nine is this one:

And merely for reference, here's that error message over again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'southward break this down!

  • TypeError is the kind of mistake

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

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

This is a proficient inkling! There are merely a few ways to read backdrop in JavaScript.

The most common is probably the . operator.

Equally in user.name, to access the name property of the user object.

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

There'southward besides brackets (aka square brackets, []) for accessing items in an array, similar items[5] or items['map'].

You might wonder why the error isn't more specific, similar "Cannot read function `map` of undefined" – but remember, the JS interpreter has no idea what we meant that blazon to be. Information technology doesn't know information technology was supposed to be an assortment, or that map is a function. It didn't get that far, considering items is undefined.

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

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

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

Information technology would exist way more 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 can piece this all together:

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

Once yous know which variable to look at, y'all can read through the function looking for where it comes from, and whether it's initialized.

In our trivial case, the only other occurrence of items is line 4:

This defines the variable but it doesn't ready information technology to anything, which means its value is undefined. There's the trouble. Fix that, and you gear up the fault!

Fixing This in the Real Globe

Of form this case 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 error like this, though.

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

Or mayhap you did pass that prop, merely the value beingness passed in is really undefined or null.

If information technology's a local country variable, maybe you're initializing the country as undefined – useState(), written like that with no arguments, will practice exactly this!

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

Any the case, though, the process is the aforementioned: start where the error is and piece of work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logdue south or utilize the debugger to inspect the intermediate values and figure out why it'south undefined.

You'll get information technology fixed! Skillful luck :)

Success! Now bank check your email.

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

Pure React plant

Learn to call back in React

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

Kickoff learning Pure React at present

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

Alan Lavender

Alan Lavender

@lavenderlens

Cannot Read Property \'filename\' of Undefined Salesforce

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

0 Response to "Cannot Read Property \'filename\' of Undefined Salesforce"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel