How to send multiple queries in one request with graphql-request while using getStaticProps?

I am currently utilizing graphCMS in combination with NextJS and have successfully implemented fetching data. However, I am facing an issue where I need to execute 2 queries on the homepage of my website - one for all posts and another for recent posts.

queries.js:

import { gql } from "graphql-request";

export const allPostsQuery = gql`
  query AllPosts {
    posts {
      title
      excerpt
      slug
      createdAt
      featuredImage {
        url
      }
      categories {
        name
        slug
      }
      author {
        bio
        name
        id
        photo {
          url
        }
      }
    }
  }
`;

export const recentPostsQuery = gql`
  query getRecentPosts {
    posts(orderBy: createdAt_DESC, last: 3) {
      title
      createdAt
      slug
      featuredImage {
        url
      }
    }
  }
`;

Exported function utilized within /pages/index.tsx:

export const getStaticHome = async () => {
  const query = queries.allPostsQuery;

  const data = await request(graphqlAPI, query);

  return data.posts;
};

getStaticProps function:

export const getStaticProps: GetStaticProps = async () => {
  // const posts = await getAllPosts();
  const posts = await getStaticHome();

  if (!posts) {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      posts,
    },
    revalidate: 60,
  };
};

However, attempting to combine both queries into a single graphql-request call results in a defined string instead of the actual Name value:

export const getStaticHome = async () => {
  const query = `
        {
           "posts": ${queries.allPostsQuery},
           "recentPosts": ${queries.recentPostsQuery}
        }
     `;

  const data = await request(graphqlAPI, query);

  return data.posts;
};

I am trying to include multiple queries in a single graphql-request, but it seems that this approach is not working as expected. Any insights into what I might be missing?

Answer №1

Resolved by ensuring distinct names for each query.

export const recentBlogPostsQuery = gql`
  query BlogPosts {
    posts: posts {
      title
      excerpt
      slug
      createdAt
      featuredImage {
        url
      }
      categories {
        name
        slug
      }
      author {
        bio
        name
        id
        photo {
          url
        }
      }
    }

    latestPosts: posts(orderBy: createdAt_DESC, last: 3) {
      title
      createdAt
      slug
      featuredImage {
        url
      }
    }
  }
`;

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

What are the best ways to integrate WordPress with React?

After experimenting with different combinations such as Gatsby, Netlify, Next.js, and more, I have been struggling to find a satisfactory workflow for developing WordPress websites using React. The solutions I have encountered so far involve too many dep ...

The `.populate()` function is malfunctioning in mongodb

As I work on developing an ecommerce application using Nextjs, one of the challenges I encountered involved populating the "reviewBy" property within an array of objects called "reviews". To tackle this issue, I attempted to populate the "reviewBy" proper ...

Using ngIf for binding

Trying to bind values based on conditions specified in *ngIf. However, when using the && operator within *ngIf, it seems to be behaving mysteriously. Sample Code: <div *ngIf="days.sunday == true"> <p class="circle ml-3" ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

What could be causing my CSS module to not have precedence over Material UI styles?

Currently, I am working with nextJs and css modules to modify the material ui classes <Toolbar classes={{ root: cn(styles.root) }} /> In order to override the material ui classes, I have followed the instructions from the material docs by using Sty ...

The object literal is limited to defining recognized properties, and 'clientId' is not present in the 'RatesWhereUniqueInput' type

Currently, I am using typescript alongside prisma and typegraphql in my project. However, I have encountered a type error while working with RatesWhereUniqueInput generated by prisma. This input is classified as a "CompoundUniqueInput" due to the database ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...

Stop the route from being displayed

I am currently working with Next.js. In my project, I have set up 3 different routes: "/", "/login", and "register". However, whenever a user accesses the "/login" or "/register" route, the "/" ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

The structure of a dynamic routing page in NextJS

I have a query the desired web URL is area/Texas/region/houston or area/Texas/region/dallas where 'area' and 'region' are static, while 'Texas' and 'houston' can vary but I am unsure of how to set up page ...

Updating the countdown label in NativeScript and Angular

I am currently working on a timer countdown component and have the following code: @Component({ moduleId: module.id, selector: 'time-countdown', template: `<StackLayout> <Label text="{{timeRemaining}}" ></La ...

Utilize a class within a Framer Motion element to incorporate animations or set initial properties

Is there a way to apply a class using Framer Motion tag in the animate and initial props? Here's an example: <motion.div initial={{ className: 'hidden' }} animate={{ className: 'visible' }} > <div>yo</div> & ...

Use a react-hook to dynamically set a custom favicon for Safari

I have a basic React hook application built with Next.js where I am trying to dynamically update the favicon. In my index.js file, I have: import React from "react"; import Head from "next/head"; import { useTheme } from "@emotion/ ...

Solve TypeScript React error TS(2339) by resolving issues with extending a React.FC and using static property of type JSX.Element for uninitialized components

Currently, in VSCode, the typescript compiler is at TypeScript React 4.4.2 and it's pointing to a TS(2339) error: Property 'Col' does not exist on type 'FC<GridProps>'. I have attempted to add this prop to GridProps: export ...

TypeScript: Despite declaring specific types, generic functions still treat parameters as "any"

When using TypeScript 4.4.3, I am looking to specify the types of function parameters for a function that returns a generic. However, TypeScript seems to be treating the parameters as any when working with functions that involve generics. Here's a si ...

Tips for monitoring dispatch in fetch/middleware functions

Just testing a basic webpage <template> <HomeTemplate /> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ async fetch(context) { // or middleware(context) await context.store.disp ...

Create a Referral Program page within a swapping interface similar to the functionalities found in platforms like PancakeSwap, PantherSwap, and

Currently, my goal is to create a referral program page similar to the one found at . I have explored the source code on GitHub for the PantherSwap interface, but unfortunately, I did not come across any references to that specific section. Would you be ...

Tips for resolving the error message "Nextjs with Typescript: 'describe' is not defined"

I am facing some obstacles while trying to compile my Nextjs project for production. Here is the list of errors that I encountered: ./components/Layout/Header/Header.test.tsx 6:1 Error: 'describe' is not defined. no-undef 7:20 Error: 'jes ...