So, I have an array of 5 people and I’m able to fetch their names and images displaying them on a page in react. I was able to do this using one asynchronous function each for the name and image. I then had two other functions that returned the names and hrefs in arrays. I’m now trying to have a card for each person displaying their name and image inside the card. I believe this can be done with the .length
function but I’m not entirely sure. The way my code works now is it only has one card and displays all 5 people in that single card. What I’m trying to do is get the length of the quarterback’s array and display a card for each item in that array.
import { Link } from "react-router-dom";
import _navbar from "../../NavBar/navbar";
import React, { useEffect, useState } from "react";
import styles from "./card.module.css";
const quarterbacks = [3139477, 4241479, 3918298, 3915511, 2577417];
const fetchFullName = async (id) => {
const res = await fetch(
`https://nfl-api-data.p.rapidapi.com/nfl-ath-fullinfo?id=${encodeURIComponent(id)}`,
{
headers: {
"x-rapidapi-key": "secret key",
"x-rapidapi-host": "nfl-api-data.p.rapidapi.com",
},
},
);
if (!res.ok) {
throw new Error(`Name lookup for id '${id}' failed`);
}
return (await res.json()).athlete.fullName;
};
// returns an array of {id, name} objects
const fetchFullNames = async (ids) =>
Promise.all(ids.map(async (id) => ({ id, name: await fetchFullName(id) })));
const fetchImage = async (id) => {
const res = await fetch(
`https://nfl-api-data.p.rapidapi.com/nfl-ath-img?id=${encodeURIComponent(id)}`,
{
headers: {
"x-rapidapi-key": "secret key",
"x-rapidapi-host": "nfl-api-data.p.rapidapi.com",
},
},
);
if(!res.ok) {
throw new Error(`Image lookup for id '${id}' failed`);
}
return (await res.json()).image.href;
}
// Returns an array of the href for each player
const fetchImages = (ids) =>
Promise.all(ids.map(async (id) => ({image : await fetchImage(id)})));
export default function _quarterbacksPage() {
const [names, setNames] = useState([]);
const [images, setImages] = useState([]);
useEffect(() => {
fetchFullNames(quarterbacks).then(setNames).catch(console.error);
fetchImages(quarterbacks).then(setImages).catch(console.error);
}, []);
return (
<>
<_navbar />
<div className={styles.card}>
{images.map(({image}) => (
<img src={image} key={image} alt="player picture"/>
))}
{names.map(({id, name }) => (
<Link className={styles.cardText} key={id} to={`/quarterback/${id}`}>
{name}
</Link>
))}
</div>
</>
);
}