I have a list card component which displays devices in a list with their name, brand, image, bookedUntil(for how long is it booked if it's booked). All of this information is coming from a Json file. I have two questions:
ListCard component:
const ReservationsListCard = ({
device: { id, name, brand, bookedUntil, quantity, image },
liked = false,
}) => {
let stateIcon;
let stateText;
var min = null;
let dateArray = [];
if (!bookedUntil) {
stateIcon = <AvailableItemIcon />;
stateText = "Available";
} else {
stateIcon = <BookedItemIcon />;
stateText = "Booked until";
dateArray = bookedUntil;
for (var i = 0; i < dateArray.length; i++) {
var current = dateArray[i];
if (min != null || current.date < min.date) {
min = current;
}
}
}
return (
<a href={"/device/" + id} className="reservations-list-card">
<img className="reservations-list-card__image" alt="device" src={image} />
<div className="reservations-list-card__brand ">{brand}</div>
<div className="reservations-list-card__name">{name}</div>
<div className="reservations-list-card__availability">
{stateIcon}
{stateText}
{console.log(min.date)}
</div>
<div className="reservations-list-card__quantity">
QUANTITY: {quantity}
</div>
</a>
);
};
ReservationsListCard.propTypes = {
device: PropTypes.object,
};
export default ReservationsListCard;
The condition if (!bookedUntil) will never run and will always go to the else block. Empty arrays are also "true".
When the bookedUntil array is empty, and you assign its first value to current you get undefined. Later when checking current.date, you basically check undefined.date which throws an error.
You need to check the array's length:
if (!bookedUntil.length) {
// ... rest of the code
}