How to write Graphql nested mutation in React.js

Graphql now a days is coming in boom, as it is faster than others communication APIs and don’t have over fetching or under fetching issues. But with the ease of advantages of Graphql sometimes we face issues while writing the queries and mutation for the Graphql. With query we can write FETCH request and with mutation we can write other 3(PUT, POST,DELETE) request. For simple queries and mutation https://www.apollographql.com/docs/tutorial/queries/ is the perfect tutorial, but when we have to write complex or nested mutation how do we write it?

Lets take an example, If we want to pass a complex object to Graphql like below:

{
    name:"",                               //STRING
    description:"",                     //STRING
    department:"",                   //STRING
    category:[],                         //Array
    manufacturer:"",                //STRING
    files:[]                                //Array of File
properties:[{                         //Array of Objects
        name:"",                        //STRING
        toggle:"",                      //Boolean
        values:[                          //Array of Objects
                {
                    name:"",               //String
                    status:"",              //Boolean
                    image:""              //File
                }
            ]
        }     
    ]
}


In above block we have nested array of objects, how we should write mutation for this nested object?? Below code is written in assumption that apollo-client, apollo-client provider, queries and mutation setup is already done in the project.

export const ADD_PRODUCT_MUTATION = gql`
mutation addProductMutation(
  $name: String!
  $description: String!
  $category: [String!]
  $manufacturer:String!
  $department:String!
  $files:[Upload!]!
  $property:[propertyInput!]!
) {
  addProduct(name: $name, description: $description, category:$category, manufacturer:$manufacturer, department:$department,files:$files, property:$property)
}`;

Here the propertyInput is the whole properties object we have defined in first block of code. We don’t have to write separate mutation or any nested mutation for content existing in properties (Array of Objects), just we have to keep in mind that the function names and the attributes name should be same as the names in backend code.

Leave a comment

Website Powered by WordPress.com.

Up ↑