'TypeError: Cannot Read Property Of X Of Undefined' When Passing Data From Parent To Child Component But Others Are Working
Solution 1:
Hi it could be that some of rows in your data do not have quotes try doing following change it should be fixed by this
change
price={statistics.quotes.USD.price}
to
price={statistics?.quotes?.USD?.price}
? checks if given variable is present and if not return null and does not throw an error
Solution 2:
As you are using the axios
call, which is asynchronous and the data of that call is not available on initial render, but it will be available later on. So to handle this you have to conditional render (render only when certain condition met)
Try this:
price={statistics?.quotes?.USD?.price}
Or you can also use Object.hasOwnProperty('key')
with ternary
and do the conditional render.
Solution 3:
Issue
Error: TypeError: Cannot read property 'USD' of undefined
is saying that statistics.quotes
is undefined.
There are 2 possible causes:
- On the initial render you are accessing too deeply into your initial state.
- On any subsequent render the
statistics
isn't updated to something you're expecting.
My guess is that your data fetching and state update is fine and it's just the initial render issue.
The initial statistics
state is an empty object ({}
), so accessing any property is fine. It's when you then go a nested level deeper into the structure that causes the issue.
<Statistics
statistics={statistics} // OK: statistics => {}
lastUpdate={statistics.last_updated} // OK: statistics.last_updated => undefined
price={statistics.quotes.USD.price} // Error: can't access USD of undefined statistics.quotes
/>
const statistics = {};
console.log(statistics); // {}
console.log(statistics.quotes); // undefined
console.log(statistics.qoutes.USD); // error!!
Solution
You can use Optional Chaining operator (?.
) or guard clauses (null checks) to protect the "access X of undefined" errors.
<Statistics
statistics={statistics}
lastUpdate={statistics.last_updated}
price={statistics.quotes?.USD?.price}
/>
<Statistics
statistics={statistics}
lastUpdate={statistics.last_updated}
price={statistics.quotes && statistics.quotes.USD && statistics.quotes.USD.price}
/>
If there's even a remote chance that your statistics
state can be updated to undefined
then apply the same fix as above but just a level shallower, i.e. statistics?.quotes?.USD?.price
.
Alternatively you can apply some Conditional Rendering of the Statistics
component where the condition is the nested properties existing on the statistics
state.
return (
<div>
//some other stuff
{statistics.last_updated && statistics.quotes && (
<Statistics
statistics={statistics}
lastUpdate={statistics.last_updated}
price={statistics.quotes.USD?.price}
/>
)}
</div>
);
Post a Comment for "'TypeError: Cannot Read Property Of X Of Undefined' When Passing Data From Parent To Child Component But Others Are Working"