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.