Last active
August 14, 2021 11:47
-
-
Save gorbypark/91917cf19d1245f52e025b42508344b1 to your computer and use it in GitHub Desktop.
A simple vue-apollo subscription example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
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