Cannot Read Property 'write' of Undefined Node Js

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this post we'll talk about how to ready this i specifically, and forth the manner you'll larn how to approach fixing errors in full general.

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

The Quick Fix

This fault usually means you're trying to employ .map on an assortment, but that assortment isn't defined however.

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

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

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

How to Notice the Fault

Starting time order of business concern is to figure out where the error is.

If you're using Create React App, information technology probably threw up a screen like this:

TypeError

Cannot read property 'map' of undefined

App

                                                                                                                          6 |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > Listing of Items < / h1 >
> ix | {items . map((particular) => (
| ^
10 | < div central = {item . id} >
xi | {detail . proper noun}
12 | < / div >

Look for the file and the line number first.

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

btw, when yous see something like /src/App.js:9:13, the way to decode that is filename:lineNumber:columnNumber.

How to Read the Stack Trace

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

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

The lines are in order of execution, with the most recent get-go.

Here's the stack trace for this error, with the only of import lines highlighted:

                                          TypeError: Cannot                                read                                  property                                '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.evolution.js:2746)                              at Object.invokeGuardedCallbackDev (react-dom.development.js:2770)                              at invokeGuardedCallback (react-dom.evolution.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.evolution.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 (alphabetize.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 side by side] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                      

I wasn't kidding when I said you could ignore most of information technology! The first 2 lines are all we intendance almost here.

The first line is the error message, 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 proper noun of our component function
  • App.js is the file where information technology appears
  • 9 is the line of that file where the mistake occurred

Let'south expect at another one:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the proper noun of the part 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 simply I wanted to country information technology explictly: when yous're looking at a stack trace, you tin almost e'er ignore whatsoever lines that refer to files that are outside your codebase, similar ones from a library.

Usually, that means you'll pay attention to only the first few lines.

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

There are some cases where you lot do intendance nearly the full stack, but they're few and far betwixt, in my experience. Things like… if you lot doubtable a bug in the library you're using, or if you think some erroneous input is making its way into library code and blowing up.

The vast majority of the fourth dimension, though, the bug will be in your own code ;)

Follow the Clues: How to Diagnose the Error

And then the stack trace told us where to look: line nine of App.js. Permit'southward open up that upwards.

Hither'due south the full text of that file:

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

Line 9 is this one:

And simply for reference, here'southward that mistake bulletin once again:

                          TypeError: Cannot read property 'map' of undefined                                    

Permit's intermission this down!

  • TypeError is the kind of error

There are a handful of congenital-in error types. MDN says TypeError "represents an fault that occurs when a variable or parameter is not of a valid blazon." (this office is, IMO, the least useful role of the error message)

  • Cannot read property ways the code was trying to read a holding.

This is a practiced clue! There are simply a few ways to read backdrop in JavaScript.

The virtually common is probably the . operator.

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

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

At that place'due south likewise brackets (aka square brackets, []) for accessing items in an array, like items[5] or items['map'].

You might wonder why the error isn't more specific, like "Cannot read role `map` of undefined" – but think, the JS interpreter has no thought what nosotros meant that type to exist. It doesn't know it was supposed to be an array, 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 1 is another corking clue. Combined with the previous bit, you lot can be pretty sure you should exist looking for .map somewhere on this line.

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

Information technology would be 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.

Then now yous can piece this all together:

  • find the line that the error occurred on (line ix, hither)
  • scan that line looking for .map
  • look at the variable/expression/whatever immediately before the .map and be very suspicious of it.

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

In our little example, the just other occurrence of items is line 4:

This defines the variable but it doesn't set it to annihilation, which means its value is undefined. There's the problem. Gear up that, and yous ready the error!

Fixing This in the Real World

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

In that location are a ton of potential causes for an fault like this, though.

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

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

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

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

Whatever the case, though, the procedure is the same: starting time where the fault is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logsouth or use the debugger to inspect the intermediate values and figure out why information technology's undefined.

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

Success! Now check your email.

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

Pure React plant

Learn to think in React

  • 90+ screencast lessons
  • Total transcripts and closed captions
  • All the lawmaking from the lessons
  • Developer interviews

Start learning Pure React now

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

Alan Lavender

Alan Lavander

@lavenderlens

Cannot Read Property 'write' of Undefined Node Js

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

0 Response to "Cannot Read Property 'write' of Undefined Node Js"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel