Typeerror: Cannot Read Property 'getparticipantbyid' of Undefined

Got an error similar this in your React component?

Cannot read property `map` of undefined

In this mail service we'll talk about how to ready this 1 specifically, and forth the way you'll acquire how to arroyo fixing errors in general.

Nosotros'll encompass how to read a stack trace, how to interpret the text of the error, and ultimately how to fix information technology.

The Quick Set

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

That's oftentimes considering the assortment is a piece of undefined state or an undefined prop.

Make sure to initialize the state properly. That ways if it will somewhen exist an array, employ useState([]) instead of something like useState() or useState(naught).

Allow's look at how we can interpret an mistake message and rails downward where it happened and why.

How to Find the Error

Showtime guild 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

                                                                                                                          six |                                                      return                                      (                                
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> ix | {items . map((detail) => (
| ^
x | < div key = {item . id} >
11 | {item . name}
12 | < / div >

Look for the file and the line number kickoff.

Here, that'south /src/App.js and line 9, taken from the light gray text above the lawmaking block.

btw, when y'all run into something like /src/App.js:9:xiii, the style 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, only the play a joke on is that unremarkably you lot can ignore almost of it!

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

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

                                          TypeError: Cannot                                read                                  property                                '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.evolution.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.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.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.return (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 (managing director.js:286)                              at be.evaluateModule (director.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.due east.              <              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 most of it! The starting time 2 lines are all we care about here.

The offset line is the error message, and every line afterward that spells out the unwound stack of office calls that led to it.

Let'due south decode a couple of these lines:

Hither nosotros have:

  • App is the proper noun of our component function
  • App.js is the file where it appears
  • nine is the line of that file where the error occurred

Let'southward look at some other i:

                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                    
  • performSyncWorkOnRoot is the name 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 only I wanted to land it explictly: when you're looking at a stack trace, y'all tin almost always ignore any 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 beginning few lines.

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

There are some cases where you practise care about the full stack, simply they're few and far between, in my experience. Things like… if you lot suspect a bug in the library yous're using, or if you lot think some erroneous input is making its manner into library lawmaking and blowing up.

The vast bulk of the time, though, the problems will be in your own code ;)

Follow the Clues: How to Diagnose the Error

Then the stack trace told us where to expect: line 9 of App.js. Let'south open up that up.

Here's 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              }              >                                          {              detail              .proper noun              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                      

Line 9 is this one:

And just for reference, hither's that error message over again:

                          TypeError: Cannot read property 'map' of undefined                                    

Let'southward break this downwardly!

  • TypeError is the kind of error

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

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

This is a expert clue! In that location are only a few ways to read properties in JavaScript.

The near common is probably the . operator.

Every bit in user.proper name, to access the name belongings of the user object.

Or items.map, to admission the map belongings of the items object.

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

You might wonder why the fault isn't more specific, like "Cannot read function `map` of undefined" – simply remember, the JS interpreter has no idea what nosotros meant that blazon to be. Information technology doesn't know it was supposed to be an array, or that map is a part. It didn't get that far, because items is undefined.

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

This one is some other groovy inkling. Combined with the previous scrap, you can be pretty sure you 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 useful if the error could say "Cannot read property `map` of items". Sadly it doesn't say that. Information technology tells you the value of that variable instead.

So now y'all can piece this all together:

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

Once you lot know which variable to expect at, you tin read through the office looking for where it comes from, and whether it'south initialized.

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

This defines the variable only information technology doesn't ready it to anything, which ways its value is undefined. In that location's the problem. Fix that, and you lot fix the mistake!

Fixing This in the Real World

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

There 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 pass it down.

Or maybe y'all did pass that prop, but the value beingness passed in is really undefined or goose egg.

If it's a local land variable, maybe y'all'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, mayhap your mapStateToProps is missing the value, or has a typo.

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

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

Success! Now check your electronic mail.

Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step arroyo, 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
  • Developer interviews

Offset learning Pure React at present

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 front end devs wanting to upskill or consolidate.

Alan Lavender

Alan Lavender

@lavenderlens

ellisknestagave.blogspot.com

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

0 Response to "Typeerror: Cannot Read Property 'getparticipantbyid' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel