Dealing with data returned by GraphQL API using axios

My current method for making the desired post request looks like this:

async function fetchMediaList(): Promise<MediaListCollection> {
  let result = {} as MediaListCollection;

  await axios
    .post<MediaListCollection>(
      "https://graphql.anilist.co/",
      {
        query: USER_LIST_CURRENT,
        variables: {
          userId: 831347,
          status: MediaListStatus.Current,
          type: MediaType.Anime,
        },
      },
      {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      }
    )
    .then((response) => (result = response.data))
    .catch((err) => {
      throw {
        error: err,
      };
    });

  return result;
}

fetchMediaList()
  .then((data) => console.log(JSON.stringify(data)))
  .catch((err) => console.log(JSON.stringify(err)));

However, the output I receive is:

{"data":{"MediaListCollection":{"lists":[{"name":"Watching","entries":[{"id":158643971,"mediaId":5081,"status":"CURRENT","score":0,"progress":10,"repeat":0,"media":{"title":{"userPreferred":"Bakemonogatari"},"coverImage":{"extraLarge":"https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx5081-YpAE43HLQKqz.png"},"format":"TV","status":"FINISHED","episodes":15,"averageScore":83,"isAdult":false,"genres":["Comedy","Drama","Mystery","Psychological","Romance"...

Subsequently, when I attempt to access list entry 0:

fetchMediaList()
  .then((data) => console.log(JSON.stringify(data.lists![0])))
  .catch((err) => console.log(JSON.stringify(err)));

I receive an empty object:

{}

It appears that the response contains a larger object called "data," is it possible to overcome this without manually specifying each type?

Answer №1

According to xadm's suggestion,

GraphQL usually wraps data within another data object (...)

The most effective way to maintain strict typing would be:

async function retrieve<T>(query: string, parameters: Object): Promise<T> {
  return await axios
    .post(
      "https://graphql.anilist.co/",
      {
        query,
        parameters,
      },
      {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      }
    )
    .then((response) => response.data.data)
    .catch((err) => {
      throw {
        error: err,
      };
    });
}

Using the retrieve function:

retrieve<MediaListCollection>(USER_LIST_CURRENT, {
  userId: 831347,
  status: MediaListStatus.Current,
  type: MediaType.Anime,
})
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

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

The function userRole consistently returns "user" regardless of the role being admin

I am facing an issue with the getTeamMembers() method while trying to identify which members are admins in a private team. Even though I am logged in as an admin, the userRole value always shows as "user". Can anyone assist me with this problem? import { ...

When using Array.find() in TypeScript, the Subscribe function does not get called

I am currently diving into Typescript and web development, but I've encountered a peculiar issue when subscribing to an event that's leaving me stumped. In my service, I'm using a BehaviorSubject to store a carId, and on a page where there&a ...

The type 'NextApiRequest' lacks the following attributes compared to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

An error has been identified in the code for a Next.js project below. The error message reads: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any ...

problems encountered when testing azure containerclient.listblobsbyhierarchy using sinon

I have developed a REST endpoint with the code "/files/lookup", which is designed to receive a query parameter folderPath and return a list of files with details, excluding content but including metadata. The endpoint connects to Azure Blob Stora ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

Sending JSON data via a GraphQl mutation

I am struggling with passing form data from the front end through graphql to my postgreql database. Instead of sending a long list of strings, I would like to use JSON for this process. Despite researching extensively on Google and reading documentation, I ...

There is no data in the $_POST array from the Http request in Angular or PHP

I've hit a roadblock with a straightforward problem, and despite my best efforts, I haven't been able to find a solution online. Here's the code that I'm struggling with: const URL = 'http://(...)/scripts/Fiabilisation_Unique.php& ...

Unable to Add Stripe Client in NestJS using (https://www.npmjs.com/package/@golevelup/nestjs-stripe)

I'm currently facing an issue while trying to integrate the GoLevelUp stripe package into my NestJs project. Although I can successfully import the package into my global app module, I'm struggling to inject a functional client into the designate ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

Classifying Union Types based on their distinct characteristics

There is a specific type with its own unique property (method) type Functions = { method: "connect", request: number, response: number, } | { method: "remove", request: string, response: string, } I aim to create a function that can handle inp ...

"Changing the name of a symbol that is automatically imported from an internal library in

Within my module, I find myself using the Element class that is implicitly imported from the "dom" internal library. However, I also need to create my custom Element class within the same module. This presents a problem due to the name collision and poten ...

Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output: for (let i = 0; i < this.arrayNumberOne[0].length; i++) { let orangeOne = this.a ...

What could be the reason for encountering an "Uncaught Runtime Error" specifically on an Android emulator while using a React app?

I'm encountering an issue when trying to launch a web-based React app on Chrome within an Android emulator. The error message I'm receiving is as follows: "Unhandled Runtime Error Uncaught SyntaxError: Unexpected Token ." Interestingly, the same ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

Implementing Typescript with React: Assigning event.target.name to state

I am facing an issue with a React state that has specific named keys defined in an interface... Despite trying a potential solution based on the state keys, I am still encountering an error... { [x: string]: string; }' provides no match for the sign ...

Navigating the intricacies of debugging sub-domains in Angular projects using Visual Studio Code (VS

Currently working on a massive project utilizing micro-services. The unique design for clients/tenants requires visiting their specific subdomain to select a particular tenant. For example, https://ClientA.localhost:4200 and https://ClientB.localhost:4200. ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

Encountering the error message "Uncaught Error: Objects are not valid as a React child" even though I am not passing objects as children in my React component

My current challenge involves mapping an array of objects, which I retrieved from an axios.get request and then passing them as children to React components. The error message that's causing trouble for me reads as follows: An Error occurred: Objects ...

Tips on extracting values from the nested array using react axios

While the renderQuestions section works fine and prints the first question, there is an issue with the renderChoices part. The desired output is to display the choices for the first question as (a.)1970 b.) 1971 c.)1972 d.)1973) but it currently displays ...

Unable to retrieve the updated value from the service variable

I'm attempting to implement a filter that allows me to search for items based on a service variable that is updated with user input. However, I am only able to retrieve the initial value from the service in my component. Service HTML (whatever is typ ...