Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

graphql - ApolloClient - How to pass array instead of string?

On the GraphQL Playground, this query works so backend is fine:

query ($CatIDs: [String]) {
  categories(where: { id: $CatIDs }) {
    id
  Name
  slug
    collections {
    id
    slug
    Name
    Description
    }
  }
}

Where the variable $CatIDs is:

["7","9","13","14"]

Now in ApolloClient, which I use with NextJS/React, I pass the array this way:

   const { data: SubCategory } = await client.query({
    query: getSubCategories,
    variables: {
      CatIDs
  },
  });

The problem is when I do that in ApolloClient, I think CatIDs get's wrapped in an additional quotation marks which makes it a String?

Or what could be the problem?

Error:

ApolloError: select distinct "categories".* from "categories" where (("categories"."id" = $1)) and ("categories"."published_at" is not null) limit $2 - invalid input syntax for type integer: "["7","9","13","14"]"

Edit:

I see now when I set the array manually, I get a valid response.

 variables: {
      CatIDs: ["1", "2", "3"]
  },

So there must be something wrong with when I set CatIDs, even though when I log it, the value looks fine.

This is how I set CatIDs:

  1. Initial Response-Object:
  { __typename: 'Category', id: '7' },
  { __typename: 'Category', id: '9' },
  { __typename: 'Category', id: '13' },
  { __typename: 'Category', id: '14' }
  1. Map over IDs:
var CatIDs = SubCatIDs.map (x => x.id);

[ '7', '9', '13', '14' ]

  1. JSON.stringify to get double-quotations:
CatIDs = JSON.stringify(CatIDs);

["7","9","13","14"]

  1. Query with CatIDs -> Error
question from:https://stackoverflow.com/questions/65876113/apolloclient-how-to-pass-array-instead-of-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solution:

  1. Don't need JSON.stringify
  2. First entry in variables needs to be in double-quotations
const { data: SubCategory } = await client.query({
    query: getSubCategories,
    variables: {
      "CatIDs": CatIDs
    },
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...