Reputation: 99
I do not what is causing the error TypeError: products.reduce is not a function
Code
import React, {useState, useEffect} from 'react';
const Checkout = ({ products }) => {
const getTotal = () => {
return products.reduce((currentValue, nextValue) => {
return currentValue + nextValue.quantity * nextValue.price;
}, 0)
};
return<div>
<div>Total: ${getTotal()}</div>
</div>
}
export default Checkout;
Thank you for your help
Upvotes: 0
Views: 4937
Reputation: 1633
As pointed out in the comments, this might be caused by products
property not having a value.
This can simply be fixed by adding a default value of the property:
import React, {useState, useEffect} from 'react';
const Checkout = ({ products = [] }) => {
const getTotal = () => {
return products.reduce((currentValue, nextValue) => {
return currentValue + nextValue.quantity * nextValue.price;
}, 0)
};
return<div>
<div>Total: ${getTotal()}</div>
</div>
}
export default Checkout;
or:
import React, {useState, useEffect} from 'react';
const Checkout = ({ products }) => {
const getTotal = () => {
return (products || []).reduce((currentValue, nextValue) => {
return currentValue + nextValue.quantity * nextValue.price;
}, 0)
};
return<div>
<div>Total: ${getTotal()}</div>
</div>
}
export default Checkout;
Or return default value earlier:
import React, {useState, useEffect} from 'react';
const Checkout = ({ products }) => {
const getTotal = () => {
if (!Array.isArray(products)) {
return 0;
}
return products.reduce((currentValue, nextValue) => {
return currentValue + nextValue.quantity * nextValue.price;
}, 0)
};
return<div>
<div>Total: ${getTotal()}</div>
</div>
}
export default Checkout;
Upvotes: 1