Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 951
Akila Devinda Avatar asked Jul 04 '26 09:07

Akila Devinda


1 Answers

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 } }`,
}),
like image 188
Pranav C Balan Avatar answered Jul 07 '26 01:07

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!