Uncaught Typeerror: Cannot Read Property 'data' of Undefined at Htmlinputelement.fail Nextcloud

Got an mistake like this in your React component?

Cannot read holding `map` of undefined

In this post we'll talk about how to set up this one specifically, and along the mode yous'll larn 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 set up information technology.

The Quick Fix

This error usually ways you're trying to use .map on an array, merely that assortment isn't divers yet.

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

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

Permit's look at how we can interpret an fault message and track down where information technology happened and why.

How to Notice the Error

First order of concern is to figure out where the error is.

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

TypeError

Cannot read belongings 'map' of undefined

App

                                                                                                                          six |                                                      render                                      (                                
vii | < div className = "App" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
10 | < div key = {particular . id} >
eleven | {particular . proper name}
12 | < / div >

Await for the file and the line number first.

Here, that'south /src/App.js and line ix, taken from the light gray text higher up the code block.

btw, when you see something similar /src/App.js:ix:xiii, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

These e'er look long and intimidating, but the play tricks is that usually you lot can ignore most of information technology!

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

Here's the stack trace for this mistake, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  belongings                                'map'                                  of undefined                                                              at App (App.js:nine)                                            at renderWithHooks (react-dom.evolution.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.development.js:2804)                              at beginWork              $one                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.development.js:15339)                              at workLoopSync (react-dom.evolution.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.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 (manager.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:three)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore well-nigh of information technology! The outset 2 lines are all we intendance well-nigh here.

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

Permit's decode a couple of these lines:

Hither we have:

  • App is the name of our component role
  • App.js is the file where information technology appears
  • 9 is the line of that file where the fault occurred

Let's wait at some other one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name of the function where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it'due south 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, similar ones from a library.

Usually, that means you'll pay attending to merely the first few lines.

Scan down the list until information technology starts to veer into file names you lot don't recognize.

In that location are some cases where you practise care virtually the full stack, but they're few and far betwixt, in my feel. Things similar… if you suspect a issues in the library you're using, or if you think some erroneous input is making its manner into library code and blowing up.

The vast bulk of the fourth dimension, though, the bug volition exist in your own code ;)

Follow the Clues: How to Diagnose the Error

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

Hither's the full text of that file:

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

Line 9 is this ane:

And simply for reference, here'due south that error message again:

                          TypeError: Cannot read property 'map' of undefined                                    

Permit's break this down!

  • TypeError is the kind of mistake

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

  • 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 backdrop in JavaScript.

The about common is probably the . operator.

As in user.proper name, to admission the name holding of the user object.

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

At that place's as well brackets (aka square brackets, []) for accessing items in an assortment, like items[v] or items['map'].

You lot might wonder why the error isn't more than specific, like "Cannot read part `map` of undefined" – but recall, the JS interpreter has no idea what we meant that blazon to exist. It 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 another nifty clue. Combined with the previous flake, you tin be pretty certain y'all should be looking for .map somewhere on this line.

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

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

And then now you can slice this all together:

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

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

In our little case, the but other occurrence of items is line iv:

This defines the variable but it doesn't set up it to anything, which means its value is undefined. In that location's the problem. Fix that, and you ready the error!

Fixing This in the Real World

Of course this example is tiny and contrived, with a unproblematic fault, and it's colocated very shut to the site of the error. These ones are the easiest to set!

There are a ton of potential causes for an fault similar this, though.

Peradventure items is a prop passed in from the parent component – and y'all forgot to pass it downwards.

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

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

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

Whatever the example, though, the procedure is the aforementioned: first where the error is and piece of work backwards, verifying your assumptions at each bespeak the variable is used. Throw in some console.logs or employ the debugger to inspect the intermediate values and figure out why it's undefined.

Y'all'll get it fixed! Expert luck :)

Success! At present check your email.

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

Pure React plant

Learn to think in React

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

Kickoff learning Pure React at present

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

Alan Lavender

Alan Lavender

@lavenderlens

taylormothre.blogspot.com

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

0 Response to "Uncaught Typeerror: Cannot Read Property 'data' of Undefined at Htmlinputelement.fail Nextcloud"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel