Search code examples
javascriptarraysreact-nativegraphqlmutation

Unable to pass array inside GraphQL mutation - React Native


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]}]}


Solution

  • 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 } }`,
    }),