3

I was building React Native Mobile Application with GraphQL. Now I've been stuck with passing array inside GraphQL mutation. I have been using redux-thunk as middleware to pass data to GraphQL mutation.

My GraphQL mutation info:

createVirtualChallenge(
name: String!
target: String!
image: String
description: String
from: String!
to: String!
selectedUsers: [String]
): VirtualChallengeResponse!

I have been passing selected users as an array which looks like this :

["5e2148d4b76df200314f4848", "5e213e6ab76df200314f47c4"]

My redux thunk fetch function is like this

   fetch(URL.BASE_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + token,
        },
        body: JSON.stringify({
          query: `mutation{ createVirtualChallenge( name:"${name}", target:"${target}", image:"${image_name}", description:"${description}", from:"${from}", to:"${to}", selectedUsers: "${selectedUsers}" , ){ success } }`,
        }),
      })
        .then(res => res.json())

All the values are passing through props using redux.

If the array length is 1, then this mutation works.. But if the array length is greater than 1 then GraphQL throws an error.

Response from the URL - {"data": null, "errors": [{"extensions": [Object], "locations": [Array], "message": "virtualChallenge validation failed: selectedUsers: Cast to Array failed for value \"[ '5e213e6ab76df200314f47c4,5e214493b76df200314f47fa' ]\" at path \"selectedUsers\"", "path": [Array]}]}

2 Answers 2

3

Remove the quotes for that argument since the quote is using for wrapping String. Since it's an array convert into a corresponding JSON string and which will be valid array input for graphql.

selectedUsers: "${selectedUsers}" ===> selectedUsers: ${JSON.stringify(selectedUsers)}

body: JSON.stringify({
  query: `mutation{ createVirtualChallenge( name:"${name}", target:"${target}", image:"${image_name}", description:"${description}", from:"${from}", to:"${to}", selectedUsers: ${JSON.stringify(selectedUsers)}  ){ success } }`,
}),
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks For the answer ! I have tried this but it throws an error -> "message": "Syntax Error: Expected :, found Float \"5e21465\""}]}
@AkilaDevinda : can u print the string and share that
@AkilaDevinda: this value mutation{ createVirtualChallenge( name:"${name}", target:"${target}", image:"${image_name}", description:"${description}", from:"${from}", to:"${to}", selectedUsers: ${selectedUsers} ){ success } }
I have print my array using console.log -> ["5e213e6ab76df200314f47c4", "5e214493b76df200314f47fa", "5e21465ab76df200314f4821"]
What happens if you need to inject a string value that sometimes needs to be null? You'll end up injecting "null" instead of null into your query. What happens if the value you're injecting is not a simple scalar but an input object type? JSON.stringify will not correctly convert more complex values like that into GraphQL syntax because JSON syntax and GraphQL syntax are not compatible. Even if this fixes your request, string interpolation is never the way to go with GraphQL queries.
|
1

You should never use string interpolation to inject values into a GraphQL query. The preferred way is to utilize variables, which can be sent along with your query as JSON object that the GraphQL service will parse appropriately.

For example, instead of

mutation {
  createVirtualChallenge(name: "someName"){
    success
  }
}

you would write:

mutation ($name: String!) {
  createVirtualChallenge(name: $name){
    success
  }
}

and then pass the value for name along with your request:

fetch(
  ...
  body: JSON.stringify({
    query: `...`,
    variables: {
      name: 'someName',
    },
  }),
)

Utilize a variable for each argument value you want to dynamically inject into your query. This is easier than trying to inject the values yourself since you don't have to worry about GraphQL-specific syntax -- you're just passing along a JSON object. You will, however, need to know the type for each argument you are replacing this way, so you'll need to refer to your GraphQL service's schema.

2 Comments

Using variables did not work for an array of strings. Do you have any better solution for this?
@Swapnil you can open a new question with all relevant details if you are unable find a resolution. Without knowing all the relevant information, it's impossible to advise you as to what is wrong.

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.