Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

Web Component Libraries: Class Mixins

These custom element class mixins give you all the features you need to connect your components to your Apollo cache without imposing a specific component library.

Installation

npm i -S @apollo-elements/mixins
yarn add @apollo-elements/mixins
pnpm add @apollo-elements/mixins

Use the ApolloQueryMixin, ApolloMutationMixin, or ApolloSubscriptionMixin to add GraphQL behaviour to any base class.

import { ApolloQueryMixin } from '@apollo-elements/mixins/apollo-query-mixin';

import { HelloQuery } from './Hello.query.graphql';

const template = document.createElement('template');
      template.innerHTML = `
        <span id="hello"></span>
      `;

class HelloQueryElement extends ApolloQueryMixin(HTMLElement)<typeof HelloQuery> {
  query = HelloQuery;

  variables = {
    name: 'Partner',
    greeting: 'Howdy',
  };

  #data = null;
  set data(data: this['data']) { this.render(this.#data = data); }
  get data() { return this.#data; }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' })
      .append(template.content.cloneNode(true));
  }

  render(data = this.data) {
    const greeting = data?.hello?.greeting ?? 'hello';
    const name = data?.hello?.name ?? 'world';
    this.shadowRoot.getElementById('hello').textContent =
      `${greeting}, ${name}!`;
  }
}

customElements.define('hello-query', HelloQueryElement);

Exports

@apollo-elements/mixins

import {
  ApolloElementMixin,
  ApolloQueryMixin,
  ApolloMutationMixin,
  ApolloSubscriptionMixin
} from '@apollo-elements/mixins';