I'm tryng to make an api call and store the data in a variable using react hooks (useEffect). The data gets stored in an array, but when I want to render it, nothing gets rendered.
const [cards, setCards] = useState<ICard[]>([]);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
(async () => {
try {
const response = await fetch(apiUrl);
if (!response.ok) throw new Error('Couldnt find the url');
setCards(initCards(await response.json()));
console.log(cards);
setLoading(false);
} catch (e) {
console.error(e.message);
// TODO: Show error alert
}
})();
}, []);
const initCards = (cards: Cats[]): ICard[] => {
let minifiedCards: ICard[] = [];
for (const card of cards) {
const { id, url } = card;
minifiedCards.push({ id, image: url, touched: false });
}
console.log(minifiedCards);
return minifiedCards;
};
return (
<div className="App">
<ScoreBoard />
{loading ? 'loading...' : <p>loaded</p>}
<CardsGrid cards={cards} />
</div>
);
const CardsGrid = ({ cards }: CardsGridProps) => (
<div className="card-grid">
<h2>Cards Grid</h2>
{cards.map((card) => {
card.id;
})}
</div>
);