Fetch information from the Anilist API

I'm currently working on a small Next.js application and I attempted to fetch data from an API (). My goal is to display a collection of Anime covers.

In order to achieve this, I had to implement GraphQL. Initially, I wanted to display the names of some animes. To get hands-on experience with GraphQL in Next.js, I followed a tutorial on this particular page. Everything worked smoothly in the tutorial, but when I tried using the AniList API, I faced difficulties. Despite trying to log as much data as possible, I couldn't get it exactly as I desired.

While logging using console.log(medias), I did successfully log the necessary information. However, when it came to displaying each value, I got stuck. If you have any suggestions, I would greatly appreciate the help.

Here's the code snippet:

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>
    );
  }

https://i.sstatic.net/C9dgV.png

Answer №1

The array medials is being used instead of an object. Therefore, the code should be modified from

Object.keys(medias).map(...

to simply

medias.map(...

Answer №2

I managed to discover the solution. The titles were not being displayed because I forgot to include a return statement. Thank you to everyone who assisted me in resolving this issue.

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>
    );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges I'm Facing with my Vue.js API Integration using axios

I am currently working on a bookstore application using Vue.js. The book data is stored in this API . However, I am encountering issues displaying the information on my HTML page with the provided function and I am struggling to identify the root cause: ...

Is there a way to display one of the divs in sequence each time the page is reloaded?

Is there a way to display the divs sequentially when the page is refreshed? For instance, on the initial load, only div 1 should appear, and with each refresh it should cycle through divs 2, 3, 4, and 5 before starting over. Below is an example I'm c ...

Styles are not applied by Tailwind to components in the pages folder

NextJS project was already created with tailwind support, so I didn't have to set it up myself. However, when I add className to an HTML element in a component within the pages/ folder, it simply doesn't work, even though the Elements panel in D ...

Unleash the power of a module by exposing it to the global Window object using the dynamic

In my development process, I am utilizing webpack to bundle and manage my TypeScript modules. However, I am facing a challenge where I need certain modules or chunks to be accessible externally. Can anyone guide me on how to achieve this? Additional conte ...

Guidelines for combining inner objects with their parent in Javascript

I need assistance with using the filter function in Angular.js because it's not working on objects. Is there a way to merge a nested object into its parent using Javascript? For example, I have the following data structure: { "data" : [ { "ch ...

Store the fetched data as JSON in the local storage

Struggling to find a solution after reading several articles, I am working on fetching a large JSON from an API and I want to cache the response in the localStorage. The goal is for the script to check for an object with the requested ID in the cached JSON ...

Literal Route Waypoints Guidance Service

I am currently working on an angularjs directive that utilizes the Google Maps Direction Service. In my controller, I have a getFunction that watches for changes in a scope variable. Once the scope variable changes, it triggers the calculateAndDisplayRoute ...

How can I dynamically modify the class name of a specific element generated during an iteration in React when another element is clicked?

My goal is to dynamically add a class to a specific element within a table row when a user clicks a remove button. The desired behavior is to disable the entire row by adding a "removed" class to the containing row div. The challenge is that there are mult ...

Enable jquery offsetParent() function

$(document).ready(function(){ $("button").click(function(){ if ($("p").offsetParent().css("background-color") === "red") { $("p").offsetParent().css("background-color", "yellow"); } else { $("p").offsetParent().c ...

The challenge of maintaining scope in AngularJS Bootstrap Modals

In my application, I am using ngRoute to load a template that includes a bootstrap modal dialog. The purpose of this modal is to prompt the user if they are sure about losing their changes when trying to leave the row they are currently editing in a table. ...

Clear all events from an HTML element and its descendants with TypeScript

Each time the page loads, I have HTML from an API that is constantly changing. Is there a way to strip away all events attached to it? The original HTML looks like this: <div id="content"> <h2 onclick="alert('hi');">Test 1< ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

What causes directive templates to be fetched from the server at times (resulting in a 304 response), while other times they are retrieved from the browser cache without

I've noticed that when I reload the page, Angular directive templates load in two different ways. The first way is when the browser sends a request to the server and receives a 304 response - everything works fine. However, the second way is puzzlin ...

The not-found.js file in Next.js is displaying an empty page rather than showing a 404 error message

My current project involves using Next.js v13.4.19 with the app router mode. However, I seem to be facing an issue with the not-found.js page located in the app folder. Whenever a non-existing route is accessed, it does not render a 404 page as expected. ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...

Why won't NextJS Image elements render on iOS 16 when they are not in the viewport initially?

I opted to implement NextJS for enhanced routing capabilities and image optimization. However, I encountered an issue with certain images failing to load properly on iOS devices. The problem arises within a scrollable horizontal container featuring Product ...

How can information be seamlessly transferred between two HTML pages using a script?

For my listview, I need to pass values like "name", "info", "hap", "lat," and "lon" to page2.html. What is the best way to achieve this? In PHP, I typically use POST or GET methods, but is there a more efficient approach? If using GET is recommended, how ...

Is there a way to detect when a CSS background image has finished loading? Does an event trigger upon completion?

I am facing an issue with my sidebar widget where there is an image background in place. On top of this, I have a search input form but I don't want the input to display until the image has fully loaded. Is there a way to add a load event handler to ...

Display the list items when the page first loads

I currently have this code snippet: <nav> <ul class="sel"> <li> <a href="#LINK1" data-title="A">A</a> </li> <li> <a href ...

Tips for efficiently transferring a retrieved object from App.js to a child component in ReactJS version 16 and above using asynchronous methods

TL;DR How can I pass a fetched object from App.js to a child component asynchronously? Do I need to wait for the data to be completely fetched before returning App.js? If so, how can I achieve this? In an attempt to create a dashboard using react-chartj ...