Nuxt Cannot Read Property 'createelement' of Undefined

Got an error like this in your React component?

Cannot read property `map` of undefined

In this post we'll talk well-nigh how to prepare this 1 specifically, and forth the way y'all'll acquire how to arroyo fixing errors in general.

We'll encompass how to read a stack trace, how to interpret the text of the fault, and ultimately how to fix it.

The Quick Fix

This error usually means you're trying to utilize .map on an array, but that array isn't defined yet.

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

Make sure to initialize the country properly. That means if it will eventually exist an array, use useState([]) instead of something similar useState() or useState(null).

Let'due south look at how nosotros can interpret an error message and track downward where information technology happened and why.

How to Find the Error

Commencement club of business is to figure out where the mistake 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" >
viii | < h1 > List of Items < / h1 >
> 9 | {items . map((item) => (
| ^
ten | < div central = {item . id} >
11 | {item . name}
12 | < / div >

Look for the file and the line number first.

Hither, that's /src/App.js and line 9, taken from the calorie-free gray text above the code block.

btw, when you come across something like /src/App.js:9:13, the mode 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 demand to read the stack trace to effigy out where the error was.

These always look long and intimidating, but the trick is that usually you tin ignore most of information technology!

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

Hither's the stack trace for this fault, with the only important lines highlighted:

                                          TypeError: Cannot                                read                                  property                                'map'                                  of undefined                                                              at App (App.js:9)                                            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.evolution.js:2770)                              at invokeGuardedCallback (react-dom.development.js:2804)                              at beginWork              $1                              (react-dom.development.js:16114)                              at performUnitOfWork (react-dom.evolution.js:15339)                              at workLoopSync (react-dom.evolution.js:15293)                              at renderRootSync (react-dom.evolution.js:15268)                              at performSyncWorkOnRoot (react-dom.development.js:15008)                              at scheduleUpdateOnFiber (react-dom.development.js:14770)                              at updateContainer (react-dom.evolution.js:17211)                              at                            eval                              (react-dom.evolution.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:seven)                              at z (eval.js:42)                              at 1000.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (manager.js:286)                              at exist.evaluateModule (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:iii)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you lot could ignore most of it! The commencement 2 lines are all we care about here.

The first line is the fault message, and every line later that spells out the unwound stack of office calls that led to information technology.

Allow'southward decode a couple of these lines:

Here we have:

  • App is the name of our component role
  • App.js is the file where it appears
  • 9 is the line of that file where the mistake occurred

Let'south look at another 1:

                          at performSyncWorkOnRoot (react-dom.evolution.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 (it's a large file!)

Ignore Files That Aren't Yours

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

Ordinarily, that ways y'all'll pay attention to only the showtime few lines.

Scan down the list until it starts to veer into file names y'all don't recognize.

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

The vast bulk of the time, though, the problems volition exist in your own code ;)

Follow the Clues: How to Diagnose the Fault

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

Here'southward the full text of that file:

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

Line 9 is this one:

And simply for reference, here's that fault message again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let's interruption this down!

  • TypeError is the kind of error

There are a scattering of built-in mistake types. MDN says TypeError "represents an error that occurs when a variable or parameter is non of a valid blazon." (this role is, IMO, the to the lowest degree useful function of the error message)

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

This is a skillful inkling! There are only a few means to read properties in JavaScript.

The almost common is probably the . operator.

Every bit in user.proper noun, to admission the name property of the user object.

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

There'due south as well 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 than specific, like "Cannot read office `map` of undefined" – only call back, the JS interpreter has no thought what we meant that blazon to exist. Information technology doesn't know it was supposed to be an array, or that map is a function. Information technology didn't get that far, because items is undefined.

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

This 1 is another great inkling. Combined with the previous bit, you can be pretty sure you should be looking for .map somewhere on this line.

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

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

And so at present you tin can piece this all together:

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

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

In our niggling example, the only other occurrence of items is line 4:

This defines the variable simply it doesn't set information technology to anything, which ways its value is undefined. In that location'due south the problem. Fix that, and you gear up the fault!

Fixing This in the Real Earth

Of form this example is tiny and contrived, with a simple mistake, and it's colocated very close to the site of the error. These ones are the easiest to gear up!

In that location are a ton of potential causes for an error similar this, though.

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

Or possibly you did laissez passer that prop, but the value being passed in is actually undefined or null.

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

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

Any the case, though, the process is the same: first 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'll get information technology fixed! Good luck :)

Success! Now check your electronic mail.

Learning React tin can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a footstep-past-step approach, 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

Commencement learning Pure React at present

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

Alan Lavender

Alan Lavender

@lavenderlens

dickeytoneve.blogspot.com

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

0 Response to "Nuxt Cannot Read Property 'createelement' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel