Jspdf Cannot Read Property 'api' of Undefined
Got an mistake similar this in your React component?
Cannot read property `map` of undefined
In this post we'll talk about how to fix this one specifically, and along the way you'll learn how to arroyo 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 error unremarkably means you're trying to apply .map
on an array, but that array isn't defined still.
That'southward frequently because the assortment is a slice of undefined state or an undefined prop.
Make sure to initialize the state properly. That means if it will eventually be an array, use useState([])
instead of something similar useState()
or useState(null)
.
Let's look at how we can interpret an mistake message and track down where it happened and why.
How to Find the Error
Start club of business is to figure out where the error is.
If you're using Create React App, it probably threw upward a screen like this:
TypeError
Cannot read property 'map' of undefined
App
6 | return (
7 | < div className = "App" >
8 | < h1 > List of Items < / h1 >
> nine | {items . map((item) => (
| ^
10 | < div fundamental = {item . id} >
11 | {item . proper noun}
12 | < / div >
Await for the file and the line number first.
Here, that'due south /src/App.js and line 9, taken from the low-cal grey text above the code cake.
btw, when y'all 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, yous'll need to read the stack trace to figure out where the error was.
These always look long and intimidating, simply the trick is that ordinarily you can ignore most of it!
The lines are in society of execution, with the well-nigh recent first.
Hither's the stack trace for this error, 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.evolution.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 $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.development.js:15008) at scheduleUpdateOnFiber (react-dom.development.js:14770) at updateContainer (react-dom.development.js:17211) at eval (react-dom.evolution.js:17610) at unbatchedUpdates (react-dom.development.js:15104) at legacyRenderSubtreeIntoContainer (react-dom.evolution.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 (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.e. < computed > [equally 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 it! The start 2 lines are all we care about here.
The get-go line is the error bulletin, and every line after that spells out the unwound stack of role calls that led to it.
Let's decode a couple of these lines:
Here we have:
-
App
is the name of our component function -
App.js
is the file where information technology appears -
ix
is the line of that file where the error occurred
Permit'due south look at another i:
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'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, yous can nearly always ignore any lines that refer to files that are outside your codebase, like ones from a library.
Commonly, that means y'all'll pay attention to but the start few lines.
Scan down the list until information technology starts to veer into file names y'all don't recognize.
There are some cases where y'all practice intendance about the full stack, but they're few and far betwixt, in my feel. Things like… if you suspect a bug in the library you're using, or if yous retrieve some erroneous input is making its way into library code and blowing upwards.
The vast bulk of the time, though, the bug will exist in your own code ;)
Follow the Clues: How to Diagnose the Error
And then the stack trace told us where to await: line nine of App.js. Let's open that upwards.
Hither'south the total 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 fundamental = { item .id } > { item .proper name } </ div > )) } </ div > ) ; }
Line 9 is this one:
And just for reference, here'south that error message again:
TypeError: Cannot read belongings 'map' of undefined
Let's suspension this downward!
-
TypeError
is the kind of fault
There are a handful of built-in fault types. MDN says TypeError "represents an error that occurs when a variable or parameter is not of a valid type." (this part is, IMO, the least useful part of the mistake bulletin)
-
Cannot read property
means the code was trying to read a holding.
This is a good clue! There are merely a few ways to read properties in JavaScript.
The most common is probably the .
operator.
As in user.name
, to access the name
holding of the user
object.
Or items.map
, to access the map
property of the items
object.
In that location's also brackets (aka square brackets, []
) for accessing items in an array, like items[five]
or items['map']
.
Y'all might wonder why the error isn't more than specific, like "Cannot read function `map` of undefined" – just remember, the JS interpreter has no idea what we meant that type to be. It doesn't know it was supposed to exist 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 one is another smashing clue. Combined with the previous bit, you can be pretty sure you should exist looking for .map
somewhere on this line.
-
of undefined
is a inkling most the value of the variable
It would be style more useful if the error could say "Cannot read holding `map` of items". Sadly it doesn't say that. It tells you the value of that variable instead.
And so now you can piece this all together:
- find the line that the error occurred on (line 9, here)
- scan that line looking for
.map
- look at the variable/expression/any immediately before the
.map
and be very suspicious of it.
In one case yous know which variable to expect at, y'all can read through the function looking for where it comes from, and whether it's initialized.
In our little example, the but other occurrence of items
is line 4:
This defines the variable only it doesn't set it to annihilation, which means its value is undefined
. There's the trouble. Prepare that, and you fix the error!
Fixing This in the Real Globe
Of course this case 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 set up!
There are a ton of potential causes for an fault similar this, though.
Maybe items
is a prop passed in from the parent component – and yous forgot to laissez passer information technology down.
Or maybe you lot did laissez passer that prop, but the value being passed in is actually undefined or null.
If it'southward a local state variable, maybe yous're initializing the state equally undefined – useState()
, written like that with no arguments, will do exactly this!
If it'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 aforementioned: kickoff where the mistake is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.log
s or employ 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 email.
Learning React can be a struggle — then many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, bank check out my Pure React workshop.
Learn to recollect in React
- 90+ screencast lessons
- Total transcripts and closed captions
- All the code from the lessons
- Developer interviews
Start learning Pure React at present
Dave Ceddia'south Pure React is a work of enormous clarity and depth. Hats off. I'g a React trainer in London and would thoroughly recommend this to all front terminate devs wanting to upskill or consolidate.
fredericksonsurries.blogspot.com
Source: https://daveceddia.com/fix-react-errors/
0 Response to "Jspdf Cannot Read Property 'api' of Undefined"
Enregistrer un commentaire