Having some trouble with this .map function saying that it's not a function.
What it's supposed to do is get the data based on the URL and then insert it into a mapped component.
Here is the component itself:
export default function Trainers() {
const [data, setData] = useState({});
const { id } = useParams();
useEffect(() => {
fetch(`http://localhost:4000/api/v1/trainers/${id}`)
.then((response) => response.json())
.then((data) => setData(data));
console.log(data);
// eslint-disable-next-line
}, []);
return (
<div>
<Pos>
<SmallHeadline>
<Cap>Trainer</Cap>
</SmallHeadline>
</Pos>
{data.data.map((course, key) => {
return (
<TrainerCard key={key}>
<TrainerImgCon
style={{ backgroundImage: `url(${course.asset.url})` }}
></TrainerImgCon>
<TrainerTxt>{course.trainerName}</TrainerTxt>
</TrainerCard>
);
})}
</div>
);
}
The API that it's taking the data from looks like this: fetched data
Appreciate any insight on this
The issue is that the initial state has nothing that is mappable
const [data, setData] = useState({});
and on the initial render you are expecting at least a data.data to exist
{data.data.map((course, key) => {
return (
<TrainerCard key={key}>
<TrainerImgCon
style={{ backgroundImage: `url(${course.asset.url})` }}
></TrainerImgCon>
<TrainerTxt>{course.trainerName}</TrainerTxt>
</TrainerCard>
);
})}
I suggest providing valid initial state
const [data, setData] = useState({ data: [] });
Or use Optional Chaining or some other null check on the mapping
{data.data?.map((course, key) => {
return (
<TrainerCard key={key}>
<TrainerImgCon
style={{ backgroundImage: `url(${course.asset.url})` }}
></TrainerImgCon>
<TrainerTxt>{course.trainerName}</TrainerTxt>
</TrainerCard>
);
})}
From what I can tell of your example response value though, perhaps there is no nested data property, and it also seems to be an object, not an array, so there may not be anything to map. The empty object ({}) data state is fine.
const [data, setData] = useState({});
...
return (
<div>
<Pos>
<SmallHeadline>
<Cap>Trainer</Cap>
</SmallHeadline>
</Pos>
<TrainerCard key={key}>
<TrainerImgCon
style={{ backgroundImage: `url(${course.asset.url})` }}
/>
<TrainerTxt>{data.trainerName}</TrainerTxt>
</TrainerCard>
</div>
);