Get Dynamic Zone Type in Graphql

Get Dynamic Zone Type in Graphql

I have Strapi set up as a headless CMS and Gatsby on the frontend. In Strapi I have a "Single" type set up with a dynamic zone that the user can use to insert various components to it.

When querying directly from Strapi GraphQL, I can get the component type, like this:

{
  inicio {
    componentes {
      __typename
    }
  }
}

Which returns:

{
  "data": {
    "inicio": {
      "componentes": [
        {
          "__typename": "ComponentPaginasCitaBiblica"
        },
        {
          "__typename": "ComponentPaginasAlerta"
        },
        {
          "__typename": "ComponentPaginasTexto"
        }
      ]
    }
  }
}

However in Gatsby, I get a different result:

query MyQuery {
  strapiInicio {
    componentes {
      __typename
    }
  }
}
{
  "data": {
    "strapiInicio": {
      "componentes": [
        {
          "__typename": "StrapiInicioComponentes"
        },
        {
          "__typename": "StrapiInicioComponentes"
        },
        {
          "__typename": "StrapiInicioComponentes"
        }
      ]
    }
  },
  "extensions": {}
}

I need to select different fields depending on the component type and be able to display them correctly on the page, however, __typename is always set to StrapiInicioComponentes. Is there another way to get this from Gatsby?

The GraphiQL explorer doesn't show anything else there:

1 Answer

There is an open bug about this. The fix has been merged, however, at the time of writing, it has only been added to an alpha release, so use at your own risk.

To install the latest alpha version of gatsby-source-strapi with npm, execute:

npm i gatsby-source-strapi@alpha

This adds the component type to strapi_component in the GraphQL.

Or as an alternative, you could try gatsby-source-rest-api, which exposes the component type under _xcomponent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.