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

Execute ReactJS function only if query parameters are configured

Provide an Explanation: Within the useEffect, I am retrieving products using the getProducts() function based on the provided data. The data contains search filters that can be updated by the user in real-time. For instance, the data consists of an object ...

Troubleshooting TestBed: Resolving the StatusBar Provider Error

After reading an informative article on testing Ionic2 projects with TestBed, I encountered difficulties when trying to replicate the example in my own environment. When attempting to initiate tests at Step 3, I encountered the error message stating "No pr ...

Can someone share their experience dealing with the typeError "immutable" in the auth.js callback function?

export const { handlers: { GET, POST }, auth, signIn, signOut, } = NextAuth({ providers: [ GitHub({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, }), ], callbacks: { ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

Encountering an issue with applying D3 fill to a horizontal stacked bar chart in Angular using TypeScript. When using .attr("fill", ..) in VSC, an error stating "No overload matches this call" is displayed

My goal is to create a stacked horizontal bar chart in d3, and I've been following the code example provided here. To showcase my progress so far, I have set up a minimal reproduction on stackBlitz which can be found here. While there are no errors ...

Next.js routes taking precedence over storybook routes

I recently completed a storybook project. Now, I am looking to integrate it with another project built on next.js. The issue is that Storybook and next.js each have their own set of routes. I want to streamline the routing process by utilizing next.js and ...

The @Prop property decorator in Vue cannot be utilized as it is not compatible

I have a Vue 2 component with TypeScript: import Vue from 'vue'; import Component from 'vue-class-component'; import Prop from 'vue-property-decorator'; @Component({ template: require('./template.html'), }) expo ...

Error: Could not locate module 'fs' in Next.js when using googleapis

I've got this snippet of code in my app/api/calendar.js file which serves to remove a single event from Google Calendar export async function deleteEventFromCalendar(accessToken, eventId) { const SCOPES = [ "https://www.googleapis.com/auth/ ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

Troubleshooting deployment issues with aws-amplify and Next.js due to conflicts in aws-exports.js

As a newcomer to web development and the react/next/amplify ecosystem, I've been experimenting with it lately and finding it to be quite impressive. However, I'm facing challenges when it comes to deploying my app. It seems like there might be an ...

Tips for incorporating moment.js library into an Angular 2 TypeScript application

I attempted to utilize TypeScript bindings in my project: npm install moment --save typings install moment --ambient -- save test.ts file content: import {moment} from 'moment/moment'; I also tried without using TypeScript bindings: npm inst ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method ...

The system is failing to recognize the union data type

My code defines various types as follows: export type Property = | BooleanProperty | NumberProperty | IntegerProperty | StringProperty | ObjectProperty | ArrayProperty; export interface OneOf { oneOf: PropertyOrKeyword[]; } export interface ...

Node OOM Error in Webpack Dev Server due to Material UI Typescript Integration

Currently in the process of upgrading from material-ui v0.19.1 to v1.0.0-beta.20. Initially, everything seems fine as Webpack dev server compiles successfully upon boot. However, upon making the first change, Node throws an Out of Memory error with the fol ...

Tips for using useState to update only the element that was clicked:

When I click the button to add a step to a chapter, it's adding a step to all chapters instead of just one. What mistake am I making? const example_chapters = [ { id: 1, title: 'Chapter 1'}, { id: 2, title: 'Chapter 2'}, ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

When working with TypeScript, it's important to note that an implicit 'any' type may occur when trying to use an expression of type 'string' to index a specific type

Currently, I'm attempting to transfer a custom hook used in Vue for handling i18n from JavaScript to TypeScript. However, I am encountering a persistent error message: An element is implicitly assigned the type 'any' due to an expression o ...