Attempting to pass a limit argument to a query in urql, Strapi, and Next JS for the Query.posts field has resulted in a combination of errors including graphQLErrors

I need help figuring out how to pass a variable for the limit parameter in my GraphQL query. I am currently working with urql, Strapi, and its GraphQL plugin in a Next.js application.

My goal is to introduce a variable for the limit to restrict the number of rows returned. Below, I will show an example along with the error code I encountered.

Working Example

import { useQuery } from 'urql'

const GET_RECENT_POSTS_QUERY = `
query {
  posts (sort: "publishedAt:DESC") {
    data {
      attributes {
        publishedAt
        title
      }
    }
  }
}
`

export default function Example() {
  const [res] = useQuery({
    query: GET_RECENT_POSTS_QUERY,
  })

  return (
    <div>
      <h3>Recent Posts</h3>
      <div>{JSON.stringify(res)}</div>
    </div>
  )
}
`

Result

Recent Posts
{"fetching":false,"stale":false,"data":{"posts":{"data":[{"attributes":{"publishedAt":"2022-09-21T05:17:29.483Z","title":"Post Number 5","__typename":"Post"},"__typename":"PostEntity"},{"attributes":{"publishedAt":"2022-09-21T05:17:13.087Z","title":"Post Number 3 ","__typename":"Post"},"__typename":"PostEntity"},{"attributes":{"publishedAt":"2022-09-20T20:08:05.611Z","title":"Post Number 4","__typename":"Post"},"__typename":"PostEntity"},{"attributes":{"publishedAt":"2022-09-01T21:04:03.717Z","title":"My Second Post","__typename":"Post"},"__typename":"PostEnt...

I'm trying to incorporate a variable to limit the result set.

Issue - Passing a Variable

My attempts have been unsuccessful, particularly when implementing something like this:

const GET_RECENT_POSTS_QUERY = `
query ($limit: Int!){
  posts (limit: $limit, sort: "publishedAt:DESC") {
    data {
      attributes {
        publishedAt
        title
      }
    }
  }
}
`

export default function Example() {
  const [res] = useQuery({
    query: GET_RECENT_POSTS_QUERY,
    variables: { limit: 3 },
  })
  // ...

Error Message

The error message starts with:

"error":{"name":"CombinedError","graphQLErrors":[{"message":"Unknown argument \"limit\" on field \"Query.posts\"

Full Error:

...

It seems that GraphQL recognizes the variable $limit, but I am unsure about the correct way to utilize it. I have been searching through documentation without success in finding a relevant example.

Answer №1

If you happen to come across this issue, I managed to resolve it by utilizing pagination feature in the Strapi GraphQL API

Perhaps it was just my misunderstanding of the documentation but I thought I'd share the solution here for reference.

Here's How I Fixed It

const GET_RECENT_POSTS_QUERY = `
query ($limit: Int!) {
  posts (pagination: {start: 0, limit: $limit}, sort: "publishedAt:DESC") {
    data {
      attributes {
        publishedAt
        title
      }
    }
  }
}
`

export default function Example() {
  const [res] = useQuery({
    query: GET_RECENT_POSTS_QUERY,
    variables: { limit: 3 },
  })
  // ...

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 methods can be used by the client-side to determine whether a file has been successfully downloaded or received from

When a client-side file download request is initiated, I dynamically create a form element with hidden attributes and submit it to the server via POST. During this process, I need to display a loading spinner that will be hidden once the download is comple ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Ways to create space around Navbar MUI for a more balanced design

Currently, I am working on designing a navigation bar using MUI. My goal is to create a navbar with some space on both sides similar to the one seen on https://i.sstatic.net/lPXyC.png If you take a look at Stackoverflow's navbar, you will notice that ...

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

HTML-Formatted Email Content

Similar Question: MailTo with HTML body I am looking to utilize JavaScript to send emails. I came across this helpful post: Sending emails with JavaScript. My goal is to include images, bold text, and color changes in the email content. Does anyone h ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Setting a value programmatically in a Material-UI Autocomplete TextField

In my React application, I am using material-ui Autocomplete and TextField components to allow users to select values from a dropdown list. However, I am looking for a way to programmatically set the input value by clicking a button, without having to choo ...

Styles are ineffective on the focus property, although they do work before the focus is applied

I'm having trouble changing the font color of the TextInput in material UI. It seems to change to white when I click away, but then reverts back to a purple-ish color (the default) when I focus on it again. I'm not sure what I'm missing here ...

Angular2+ does not return any elements when using .getElementsByClassName() even if they are present

I have a question that seems simple, but I can't seem to find the answer anywhere. I've looked through past questions but still haven't found a solution... In my Angular template, there is a large amount of text inside a div, and some parts ...

Retrieve information from jsonObject

Can anyone help me with counting the number of passes and fails for each subject in a JSON object array? Here is an example: [{"Subject":"Maths","status:"Pass"},{"Subject":"Maths","status:"Pass"}, {"Subject":"Maths","status:"Fail"},{"Subject":"Maths ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

JavaScript Event Listener not Working Properly

I've been attempting to implement a feature on my website where the header hides when scrolling down and re-appears when scrolling up. However, I'm struggling to make use of the code snippet below to achieve this functionality. Despite my thoroug ...

Steps to establish the starting value as 'Concealed'

I stumbled upon this interesting example that demonstrates how to create expandable/collapsible text when clicked. My question is, how can I initially set the value to be hidden so that the paragraph starts off collapsed and expands only when clicked? He ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...

Is there someone who can assist me in transferring data from an Axios JSON response to plot points on a line chart using Chart js?

I'm currently in the process of developing a React application that includes a line chart showcasing the timeline of data recordings starting from a specific point in time up to the present day. To achieve this, I am leveraging the Chart.js JavaScript ...

Tips for accessing files following the transmission of a post request within the req.body

Encountering a problem where image uploads to an s3 bucket are not successful. The error message received is: API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests. The front end includes an input that ca ...

I am currently facing a challenge in React Highcharts where I am unable to remove and redraw the graph easily

Having an issue where I can't remove and redraw the chart in my React Highchart project. I've been unable to find a solution for this problem. Here is the code snippet: import { useState, useEffect, useRef } from "react"; import Highch ...