I'm developping a small next.js app and I tried to fetch from an API (https://anilist.gitbook.io/anilist-apiv2-docs/). Because I want to display a set of Anime's cover.
To do so I had to use graphQl. First I would like to manage to display the name of some animes. To practice the use of graphQl in next.js I followed the tutorial on this page. All went good I had no problem, so I tried with the anilist api but I did not succeed I tried to log data as deep as I can, but not as I wanted.
When I log by doing console.log(medias) I do manage to log the wanted informations. But when it comes to apply this to display each values I turn around. If you have an idea i'll appreciate.
Thanks for helping =)
This is the code:
import { useQuery, gql } from "@apollo/client";
const QUERY = gql`
query GetFirstsThree{
Page(page: 1, perPage: 3) {
media {
id
coverImage {
medium
}
title {
userPreferred
}
}
}
}
`;
export default function AnimList() {
const { data, loading, error } = useQuery(QUERY);
if (loading) {
return <h2>Loading...</h2>;
}
if (error) {
console.error(error);
return null;
}
const medias = data.Page.media;
return (
<div className="mainGrid">
<h1>Hello World</h1>
{medias.map((value) => {
<div key={value.id} className="card">
<h3>
{value.title.userPreferred}
</h3>
</div>
})}
</div>
);
}
The variable medias contains array and not an object. So instead of
Object.keys(medias).map(...
you need to do just
medias.map(...
I found the answer. The titles wasn't displayed because I didn't return them Thanks everyone for helping me
import { useQuery, gql } from "@apollo/client";
const QUERY = gql`
query GetFirstsThree{
Page(page: 1, perPage: 3) {
media {
id
coverImage {
medium
}
title {
userPreferred
}
}
}
}
`;
export default function AnimList() {
const { data, loading, error } = useQuery(QUERY);
if (loading) {
return <h2>Loading...</h2>;
}
if (error) {
console.error(error);
return null;
}
const medias = data.Page.media;
console.log(medias)
return (
<div className="mainGrid">
{medias.map((value) => {
// It just needed the return like below
return <div key={value.title.userPreferred} className="card">
<p>{value.title.userPreferred}</p>
</div>
})}
</div>
);
}