I'm receiving some transaction data from an API. One of the items in this return is buyer which sometimes can be null. Therefore I'm omitting any buyers that have null. This creates a varying number of results. Ideally I would like to show 5 cards and if there is only 1 result, then I'll figure out some place holder for the 4 other cards. The problem is when I have more than 5 results because it will create an additional card. I'm trying to find a solution that will limit it to 5. I can't achieve this by altering the API filters because of this "buyer = null" condition. Is there anything that can be done using a styles file or any JS/React code that I can add that will allow me to max it out?
Currently I have not brought in the Card component and am working only with list items.
return (
<ul>
{highestBuy.map((result) => {
const {
buyer,
price: { amount, token_symbol },
} = result;
if (!highestBuy) {
return (
<div>
<Spinner />
</div>
);
}
if (buyer !== null) {
return (
<li>
{buyer}
{amount}
{token_symbol}
</li>
);
}
})}
</ul>
);
There's several ways of doing this but there a moderately simple version.
// test array of fewer than 5 items
const cardsA = [{
buyer: "Adam"
}, {
buyer: "Bill"
}, {
buyer: null
}];
// more than 5 items
const cardsB = [{
buyer: "Adam"
}, {
buyer: "Bill"
}, {
buyer: null
}, {
buyer: "Charlie"
}, {
buyer: null
}, {
buyer: "David"
}, {
buyer: "Ernie"
}, {
buyer: null
},
{
buyer: "Frank"
}
];
const makeFive = (cards) => {
// filter out the nulls
cards = cards.filter(card => card.buyer !== null);
// make a new array to hold the cards
const newCards = [];
// loop 5 times
for (let ix = 0; ix < 5; ix++) {
// push a card from the filtered stack or a placeholder
// card if the filtered stack is too small
newCards.push(cards[ix] || {
buyer: "default"
});
}
// return the new cards
return newCards;
}
console.log("cardsA", makeFive(cardsA));
console.log("cardsB", makeFive(cardsB));