Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql.

My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names.

In my react code, I have a query that works in the playground:

import { gql } from "@/node_modules/@apollo/client/core/index";

export const FONT_DATA = gql`
    query font_data{
        fonts{
            data{
                attributes{
                    font_name
                }
        }
    }
}
`

I am using codegen to generate types for the fonts.

// Types generated by codegen go here

In my react page, I am calling the query and attempting to display the font names:

// React code to call the query and display font names goes here

However, I encounter an error when trying to map over the data because it's not an array.

The console log also confirms that the data is not an array.

The graphql response returns an object, so how can I use that with the map function, or should I be using a different type?

Update:

If I log the data using

console.log(JSON.stringify(data, null, 2))
, I see:

// Logged data response from graphql query goes here

Answer №1

Not quite sure about the workings of strapi, but typically a graphql response is structured as follows:

data.nameOfYourResolver.arrayObjectOrOtherTypeOfData

Your data types seem to be incorrect. In this scenario, a proper structure would look something like this:

export type FontEntityResponse = {
  fonts: Maybe<FontEntityData>; //object
};

export type FontEntityData = {
  data: Maybe<FontEntity[]> //Array
};

export type FontEntity = {
  attributes: Maybe<Font>; //Object

export type Font = {
  fontName: Maybe<string>; //string



data.fonts.data(attribute => {
   console.log(attribute.font_name)
//...
})

Although it's unclear what specific data type this is, your property names are incorrectly labelled.

You simply need to verify the types assigned to these properties

fonts{
       data{
            attributes{
               font_name }}}

You can

console.log(JSON.stringify(data, null, 2))
to view all the contained data

Additionally, in

const {data, loading} = useQuery<FontEntityResponse, FontEntity>(FONT_DATA)

The term FontEntity should ideally be utilized for variable types related to fetching this resolver.

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

"Encountered a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

What is the process for accessing a duplicated URL in the web browser?

I'm currently experimenting with a webpage that creates URLs. While I can easily copy the URL to my clipboard by clicking on an icon, I'm facing difficulties when it comes to opening it in a browser. This is a crucial test for me and I need to co ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

Troubleshooting issues with accessing the _id property using Typescript in an Angular application

Encountering an Angular error that states: src/app/components/employee/employee.component.html:67:92 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is ...

Passing a JSON object between pages in Next.js using props during programmatic navigation

In my Next.js project, I have two pages. On the first page, the user fills out a form to create a post. The information is stored in a large JSON object, which needs to be passed to the second page for the user to preview the post before finalizing it. Wi ...

Angular Form Validations - input values must not match the initial values

These are my current reactive form validations: ngOnInit(): void { this.userForm = this.formBuilder.group({ status: {checked: this.selectedUser.status == 1}, username: [this.selectedUser.username, [Validators.required, Validators.minLeng ...

Transformation occurs once you subscribe to an observable entity

Within the x.component.ts, I initiate the getSomething() method from y.service.ts. Since this method returns an observable, I subscribe to it. However, I encounter a peculiar issue where an object with 4 elements, one being an array of number arrays (numbe ...

Tips for customizing the appearance of an active link in a mapped navigation bar

I am currently working on a Next.js page and I want to add some styling to the NavBar to indicate to the user which page they are on. Although I found this interesting solution on Stack Overflow - Target Active Link when the route is active in Next.js ... ...

Compiling TypeScript files for Angular 2 with Atom can be quite time-consuming

Currently, I am utilizing Angular 2 RC-6 by referencing the Angular2 Documentation. However, I have encountered an issue with Atom being too slow to compile my '.ts' files. Interestingly, when I relocate my tsconfig.json file from the root folder ...

What to do when encountering the error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"?

While signing in to my website from localhost is successful, I encounter an issue when trying to do the same from my production build. The login attempt from the prod build (hosted on Vercel) does not post to , but instead goes to . I am perplexed by the a ...

Is there a way to programmatically allow users to customize their domain and have it redirect to my server?

I am in the process of developing a website builder. At present, users have the ability to generate a static page and utilize our subdomain for access - like mysite.site.domain.com. My initiative involves enabling users to link their own domains to redire ...

Send search engines to a particular route, like 'mydomain.com/somepath'

My website is built using Next.js. I am aiming to have the main application on the index route: ...mydomain.com/. However, I also want a dedicated landing page at route: ...mydomain.com/mylandingpage. My question revolves around how to inform search eng ...

What could be the reason for TypeScript throwing an error that 'product' does not exist in type '{...}' even though 'product' is present?

Structure of Prisma Models: model Product { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String price Float image String createdAt DateTime @default(now()) updatedAt Da ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Next.js shallow routing is not functioning as expected when a query string is added

The issue at hand: When attempting shallow routing in Next.js by changing the query string (adding or removing, but not updating), the page is reloaded and the shallow option is ignored. Is there a way to prevent reloading while modifying the query strin ...

Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons sho ...

Encountering an issue while trying to execute the getServerSideProps function within _app.js in Next

I'm looking to gain a better understanding of how to utilize a specific function for retrieving session information and where would be the best placement for my Navigation component. Currently, I have my navigation bar nested within the _app.js file ...

Error encountered with ts-loader in the node_modules/@types directory within Webpack

After successfully compiling my project, I encountered errors when trying to run npm install and then webpack in a new directory. The errors are as follows: ERROR in /home/nobody/myproject/server/node_modules/@types/mongodb/index.d.ts (500,12): error TS10 ...

Pages that utilize the `getServerSideProps` function cannot be exported

I seem to be a bit confused here. Based on the documentation, if I want Server Side Rendering (SSR) for the page, I need to export the async function: getServerSideProps However, when I try to build or deploy the project locally or on Zeit now, I encoun ...