Passing array of strings to a GraphQL query, convers to integers when embedded

Elena picture Elena · Aug 16, 2018 · Viewed 7.5k times · Source

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.

Answer

Sohail Arif picture Sohail Arif · Nov 20, 2018

A simple solution to your problem is as follows:

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