I'm building an app around the card game Magic, where you can paste a list of cards into a textbox and click a button to show card images. I use fetch and an external site API. Logging shows no errors, but the result is very inconsistent - sometimes only 1 card is shown, sometimes 2, 4, 7 etc... I need to always render all the data. I've tried for days with this.
const handleClick = async () => {
textarea.split("\n").forEach(async (items) => {
try {
const response = await fetch(
`https://api.scryfall.com/cards/named?exact=${encodeURIComponent(
items
)}&pretty=true`
);
console.log("response.status: ", response.status);
if (!response.ok) {
throw new Error(`Error! ${response.status}`);
}
const result = await response.json();
console.log("result" + result);
objects.sort(() => Math.random() - 0.5);
objects.push(result);
} catch (err) {
console.log(err);
} finally {
setIsLoading(false);
setScrydata(objects);
}
});
};
From the console.log I see everything is fetched, but sometimes in "batches", for example first 2, then 5. This is the problem I think(?) cause only 2 cards are then rendered. Is Promise.all the solution somehow? I've tried it but couldn't get it to work, I changed
const result = await response.json();
to
const result = await Promise.all([response.json()]);
but it doesn't work, the results are still in "batches".
Big thank you in advance for any help.
Edit, this is how I render the images:
{scrydata.length > 0 && (
<img
src={scrydata[0].image_uris?.normal}
key={scrydata[0].id}
alt="asdf"
/>
)}
{scrydata.length > 1 && (
<img
src={scrydata[0].image_uris?.normal}
key={scrydata[0].id}
alt="asdf"
/>
)} ... etc
Up to seven, which is the max. This shows images, but it's inconsistent; I want seven every time. Maybe this code could be my problem. Thanks again.