I have a simple React app(created with vite), where i am passing a list of objects to a component Carts, Carts component simply parses the list and returns JSX. But there is a error pointing that the passed list to the Carts component is not reaching, it is reaching as undefined, also i noticed that Carts is getting called multiple time, (i am in strict mode, but i believe even in strict mode it is called only 2 times.) and in those extra calls it is not getting props properly.
Error Msg:
TypeError: Cannot read properties of undefined (reading 'length')
at Carts (Carts.jsx:13:16)
at renderWithHooks (chunk-M324AGAM.js?v=aec0e7ae:11546:26)
at mountIndeterminateComponent (chunk-M324AGAM.js?v=aec0e7ae:14924:21)
at beginWork (chunk-M324AGAM.js?v=aec0e7ae:15912:22)
at HTMLUnknownElement.callCallback2 (chunk-M324AGAM.js?v=aec0e7ae:3672:22)
at Object.invokeGuardedCallbackDev (chunk-M324AGAM.js?v=aec0e7ae:3697:24)
at invokeGuardedCallback (chunk-M324AGAM.js?v=aec0e7ae:3731:39)
at beginWork$1 (chunk-M324AGAM.js?v=aec0e7ae:19763:15)
at performUnitOfWork (chunk-M324AGAM.js?v=aec0e7ae:19196:20)
at workLoopSync (chunk-M324AGAM.js?v=aec0e7ae:19135:13)
Carts.jsx Code
const Carts = ({ listCart }) => {
//below console log is getting printed 4 times
console.log("inside listCart");
let topMessage;
//here the listCart is reaching empty
if (listCart.length === 0) {
topMessage = `No Products in Cart`;
} else {
topMessage = `Cart Elements`;
}
return (
<Carts>
<h1>{topMessage}</h1>
{listCart.map(({ name, description, price, _id }) => (
<Cart name={name} description={description} price={price} key={_id} />
))}
</Carts>
);
};
export default Carts;
App.jsx
function App() {
const list = [
{
name: "Digital Camera",
description:
"A digital camera with a 24MP sensor and 4K video recording capabilities.",
_id: 9,
price: 600,
},
];
return (
<div className="carts">
<Carts listCart={list} />
</div>
);
}
export default App;
My Observation: If i print something inside Carts component, its getting printed 4 times, once is okay , second one is called by react to check for purity,that is also fine, but then again it gets called two times and receives listCart as undefined.
In the returned JSX template of your Carts
component, you make a recursive call to itself, with no props:
const Carts = ({ listCart }) => {
// etc.
return (
<Carts> {/* Recursive call without props */}
<h1>{topMessage}</h1>
{/* etc. */}
</Carts>
);
};
This is very likely the reason for your extra 2 calls.
You probably want to use a React Fragment instead, e.g. using the diamond notation:
const Carts = ({ listCart }) => {
// etc.
return (
<> {/* Or <React.Fragment> */}
<h1>{topMessage}</h1>
{/* etc. */}
</>
);
};