9

I'm trying to figure out a way to pass an array of strings and embed it into a query (using React, GraphQL). The problem is it accepts the parameter as an array of strings, but converts it to a string when I embed it.

Let's say I have this function that makes a call to get some data. (I hardcoded the argument for now but it will be a variable as soon as I figure this out).

// here I'm calling the function

 const query = getData.generate(["123", "456"]);
        return GraphqlClient.query(query)
        .then((e) => {
            return e.data.oneAppProviders;
        }) .......

// and here is the query with the embedded parameter. (Backend expects an array of strings.)

export default {
generate(id) {
// console.log(id)        // output: ["123", "456"]
    return { query : gql`{
        oneAppProviders(id: ${id}) {
            id
            firstName
         }
    }
}}

When I run it, I get this error:

GraphQLError {message: "Syntax Error: Expected Name, found Int "456""

I guess, when I embed it, it converts it to integers... If my array is ["123"], I get the following error:

[GraphQL error]: Message: Expected type [String], found 123.

I hope the question is clear enough. Thanks in advance.

3 Answers 3

8

Maybe this helps someone:

export const UserFlagsQuery = gql`
  query($flags: [String!]!) {
    user {
      flags(where: { AND: [{ name_in: $flags }, { enabled: true }] }) {
        name
        enabled
      }
    }
  }
`;

Use this query in a React Query component like this:

<Query
  query={UserFlagsQuery}
  variables={{
    flags: ["flag1", "flag2", "..."],
  }}
>

Thanks to @David Maze answer.

Sign up to request clarification or add additional context in comments.

Comments

5

As a general rule you should avoid embedding data into query language strings like this. (What if the id variable is actually a string containing parentheses and curly braces? https://xkcd.com/327 is a more famous, if fictional, example of the potential problems you're facing.)

GraphQL supports top-level query parameters and you should use those here. If you make your query like

query Providers($ids: [ID!]!) {
    oneAppProviders(id: $ids) {
        id
        firstName
     }
}

most query libraries have a way to pass in additional parameters; so in your case that might look like

const query = gql`...`;
const variables = { ids: ids };
GraphqlClient.query(query, variables).then(...);

Comments

4

A simple solution to your problem is as follows:

let myarray = ["string1", "string2", "String3"];
let dataToSend = myarray.toString();
let gql`
{
   passArray(data:${dataToSend}){
   }
}`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.