Error Typeerror: Cannot Read Property 'token' of Undefined
Got an error like this in your React component?
Cannot read property `map` of undefined
In this postal service we'll talk about how to fix this one specifically, and forth the mode you'll learn how to arroyo fixing errors in general.
We'll cover how to read a stack trace, how to interpret the text of the mistake, and ultimately how to set information technology.
The Quick Prepare
This mistake commonly means you're trying to use          .map          on an array, simply that array isn't defined yet.
That'southward oftentimes considering the array is a piece of undefined land or an undefined prop.
Brand sure to initialize the state properly. That means if information technology will          somewhen          be an array, use          useState([])          instead of something like          useState()          or          useState(cypher).
Let's look at how nosotros can translate an error bulletin and rail downward where it happened and why.
How to Notice the Fault
Starting time order of business is to effigy 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"                                    >                                                  
                                                                                          viii |                                                                        <                                    h1                                    >                                    List                                      of                                    Items                                    <                                    /                                    h1                                    >                                                  
                                                                      >                                                                          9 |                                                        {items                  .                  map((item)                                    =>                                      (                                
                                                                                          |                                                                                          ^                                                                    
                                                                                          10 |                                                                        <                                    div                                      key                  =                  {particular                  .                  id}                  >                                                  
                                                                                          11 |                                                        {item                  .                  name}                                
                                                                                          12 |                                                                        <                                    /                                    div                                    >                                                                                        Await for the file and the line number first.
Here, that'southward /src/App.js and line 9, taken from the light grayness text above the code block.
btw, when yous see something like          /src/App.js:9:thirteen, the way 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 need to read the stack trace to effigy out where the error was.
These ever look long and intimidating, but the trick is that normally you can ignore most of it!
The lines are in order of execution, with the most recent first.
Hither'southward 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.evolution.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.evolution.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.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.evolution.js:17609)                              at Object.render (react-dom.evolution.js:17672)                              at evaluate (index.js:7)                              at z (eval.js:42)                              at Thousand.evaluate (transpiled-module.js:692)                              at be.evaluateTranspiledModule (managing director.js:286)                              at exist.evaluateModule (manager.js:257)                              at compile.ts:717                              at l (runtime.js:45)                              at Generator._invoke (runtime.js:274)                              at Generator.forEach.e.              <              computed              >                              [as next] (runtime.js:97)                              at t (asyncToGenerator.js:3)                              at i (asyncToGenerator.js:25)                              I wasn't kidding when I said y'all could ignore almost of it! The commencement 2 lines are all nosotros intendance almost here.
The first line is the error message, and every line subsequently that spells out the unwound stack of function calls that led to it.
Let'southward decode a couple of these lines:
Hither nosotros have:
-             Appis the proper noun of our component function
-             App.jsis the file where it appears
-             9is the line of that file where the mistake occurred
Let'south look at some other one:
                          at performSyncWorkOnRoot (react-dom.development.js:15008)                                            -             performSyncWorkOnRootis the name of the function where this happened
-             react-dom.development.jsis the file
-             15008is the line number (it's a large file!)
Ignore Files That Aren't Yours
I already mentioned this only I wanted to state it explictly: when you lot're looking at a stack trace, you tin almost always ignore whatever lines that refer to files that are outside your codebase, like ones from a library.
Ordinarily, that ways you'll pay attention to only the first few lines.
Scan down the listing until it starts to veer into file names yous don't recognize.
There are some cases where you do care most the full stack, but they're few and far between, in my experience. Things like… if you suspect a problems in the library you're using, or if you lot think some erroneous input is making its mode into library code and bravado up.
The vast majority of the time, though, the issues volition be in your ain lawmaking ;)
Follow the Clues: How to Diagnose the Error
So the stack trace told us where to look: line 9 of App.js. Let's open that up.
Hither's the full text of that file:
                          import                                          "./styles.css"              ;              export                                          default                                          function                                          App              ()                                          {                                          allow                                          items              ;                                          return                                          (                                          <              div                                          className              =              "App"              >                                          <              h1              >              List of Items              </              h1              >                                          {              items              .              map              (              item                                          =>                                          (                                          <              div                                          key              =              {              detail              .id              }              >                                          {              detail              .name              }                                          </              div              >                                          ))              }                                          </              div              >                                          )              ;              }                              Line 9 is this one:
And just for reference, here'due south that mistake message again:
                          TypeError: Cannot read property 'map' of undefined                                            Allow's break this down!
-             TypeErroris the kind of error
There are a handful of built-in error types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this office is, IMO, the least useful part of the fault bulletin)
-             Cannot read propertymeans the code was trying to read a property.
This is a skilful inkling! At that place are only a few ways to read backdrop in JavaScript.
The most common is probably the          .          operator.
As in          user.name, to access the          name          property of the          user          object.
Or          items.map, to access the          map          belongings of the          items          object.
There's also brackets (aka square brackets,          []) for accessing items in an assortment, like          items[v]          or          items['map'].
You might wonder why the error isn't more than specific, like "Cannot read          function          `map` of undefined" – just remember, the JS interpreter has no thought what we meant that type to be. It doesn't know it 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 great clue. Combined with the previous bit, you tin be pretty sure you should be looking for          .map          somewhere on this line.
-             of undefinedis a clue almost the value of the variable
It would exist way more than useful if the error could say "Cannot read property `map` of items". Sadly it doesn't say that. Information technology tells yous the value of that variable instead.
So now y'all tin piece this all together:
- detect the line that the mistake occurred on (line ix, hither)
- scan that line looking for            .map
- look at the variable/expression/whatever immediately before the            .mapand be very suspicious of it.
Once you know which variable to look at, y'all can read through the function looking for where it comes from, and whether it'due south initialized.
In our trivial example, the but other occurrence of          items          is line iv:
This          defines          the variable but information technology doesn't ready it to anything, which ways its value is          undefined. There'southward the problem. Ready that, and you set the error!
Fixing This in the Real World
Of course this example is tiny and contrived, with a uncomplicated mistake, and it's colocated very close to the site of the mistake. These ones are the easiest to fix!
There are a ton of potential causes for an error similar this, though.
Mayhap          items          is a prop passed in from the parent component – and yous forgot to pass it down.
Or perchance y'all did pass that prop, but the value being passed in is actually undefined or null.
If it's a local country variable, maybe you're initializing the state as undefined –          useState(), written like that with no arguments, will do exactly this!
If it's a prop coming from Redux, maybe your          mapStateToProps          is missing the value, or has a typo.
Whatever the case, though, the process is the aforementioned: start where the error is and work backwards, verifying your assumptions at each indicate the variable is used. Throw in some          console.logsouthward or utilise the debugger to inspect the intermediate values and figure out why it's undefined.
You'll get it fixed! Good luck :)
Success! Now check your e-mail.
            Learning React tin be a struggle — and so many libraries and tools!
            My advice? Ignore all of them :)
            For a footstep-by-pace approach, cheque out my Pure React workshop.          
               
            
Learn to think in React
- xc+ screencast lessons
- Full transcripts and airtight captions
- All the lawmaking from the lessons
- Programmer interviews
Get-go learning Pure React now
Dave Ceddia's Pure React is a work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all forepart stop devs wanting to upskill or consolidate.
Source: https://daveceddia.com/fix-react-errors/
 
              
0 Response to "Error Typeerror: Cannot Read Property 'token' of Undefined"
Postar um comentário