Search code examples
graphqlstrapi

How to: Strapi GraphQL mutation with dynamic zones/component


I am trying to create a mutation for Strapi that creates/edits dynamic zones. Dynamic zones in Strapi are union types. How does one do a GraphQL mutation with dynamic zones?

To be exact. What should be the content here?

input: {data: {inhalt: [{text: "hallo"}]}}

In the example below there is a single component named impressum. Inhalt is the dynamic zone. It contains different components: ComponentPageText, ComponentPageInformation and ComponentPageArticle.

This mutation

mutation {
  updateImpressum(input: {data: {inhalt: [{text: "hallo"}]}}) {
    impressum {
      inhalt {
        __typename
      }
    }
  }
}

returns

Expected type ImpressumInhaltDynamicZoneInput!, found {text: \"hallo\"}; Component not found. expected one of: ComponentPageText, ComponentPageInformation, ComponentPageArticle

This returns the same error

mutation {
  updateImpressum(input: {data: {inhalt: [{ComponentPageText: {text: "hallo"}}]}}) {
    impressum {
      inhalt {
        __typename
      }
    }
  }
}

Schema introspection returns

{
  "name": "ComponentPageText",
  "kind": "OBJECT"
}

STRUCTURE (added after comment)

impressum => inhalt => [page.text, page.information, page.article]

corresponds to

single type => dynamic zone => [components]

Fields in components

page.text: text
page.information: title, text, image
page.article: relation to collection type - article

SCHEMA INTROSPECTION

{
  "name": "updateImpressum",
  "__typename": "__Field",
  "description": "",
  "args": [
    {
      "name": "input",
      "description": "",
      "__typename": "__InputValue",
      "type": {
        "kind": "INPUT_OBJECT",
        "name": "updateImpressumInput",
        "possibleTypes": null,
        "interfaces": null,
        "inputFields": [
          {
            "name": "data",
            "description": "",
            "__typename": "__InputValue"
          }
        ]
      }
    }
  ]
}

Solution

  • Here is an example of how to mutate a dynamic zone in Strapi. In my case, I have a collection called Tests and a dynamic zone called New Question that is under a group called questions-group:

    mutation {
     createTest(input:{ data:{
      title:"Test Title Here"
      questions: [
         {
          __typename: "ComponentQuestionsGroupNewQuestion"
          __component: "questions-group.new-question"
          title:"What is 4 + 20?"
          correct_answer: "24"
          wrong_answer: "420"
        }
      ]
      }}) {
        test {
          id
        }
      }
    }
    

    You have to provide __typename: and __component: inside the dynamic zone clause.