Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lustremedia/215215bf2c235fbd26cf3463b3ec726e to your computer and use it in GitHub Desktop.
Save lustremedia/215215bf2c235fbd26cf3463b3ec726e to your computer and use it in GitHub Desktop.
A simple vue-apollo subscription example
<!--
This is a simple vue single file component example of using a subscription with vue-apollo.
This starts out as a query, and then if there are any changes to the underlying data,
the subscription updates it. The subscription works by holding open a websocket connection
to the GraphQL server. This was tested using Hasura.io and PostgreSQL, but should work with
any GraphQL implementation that supports websocket subscriptions. In the example, the
PostgreSQL table would be in a schema named "myschema" and a table named
"mytable" and that table would have two columns, "id" and "name".
-->
<template>
<div>
<!-- Here we "loop" through all items contained in the data property "items" -->
<span v-for="item in items" :key="item.id">
<!-- And we print out the name contained within items -->
{{ item.name }}
</span>
</div>
</template>
<script>
import gql from "graphql-tag";
export default {
data: () => ({
items: {} // This is where we store our graphql results. It starts out blank.
}),
apollo: {
items: { // Apollo will store query results in this key in the data properties, so it must match a data property of the same name.
// below is the "initial" query
query: gql`
{
myschema_mytable {
id,
name
}
}
`,
update(data) { // This function returns our QUERY into the data property "items" when the component is loaded.
return data.myschema_mytable;
},
subscribeToMore: {
// below is the subscription query.
document: gql`
subscription mySubscription {
myschema_mytable {
id,
name
}
}
`,
updateQuery: (previousResult, { subscriptionData }) => {
return subscriptionData.data; // This returns our SUBSCRIPTION into the data property "items" when there is an update
}
}
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment