Create Subscription and Render Result

Add subscription query

So let's define the graphql subscription to be used.

Open src/components/OnlineUsers.vue and add the following code, below the other import.

githubsrc/components/OnlineUsers.vue
<script>
import gql from 'graphql-tag'
+ const SUBSCRIPTION_ONLINE_USERS = gql`
+ subscription getOnlineUsers {
+ online_users(order_by: {user: {name: asc }}) {
+ id
+ user {
+ name
+ }
+ }
+ }
+ `;

We are defining the graphql subscription query to fetch the online user data. Now let's define a smart subscription.

export default {
data() {
return {
online_list: [
{ user: { name: "someUser1" }},
{ user: { name: "someUser2" }}
]
};
},
mounted() {
...
},
+ apollo: {
+ // Subscriptions
+ $subscribe: {
+ // When a user is added
+ online_users: {
+ query: SUBSCRIPTION_ONLINE_USERS,
+ // Result hook
+ result (data) {
+ // Let's update the local data
+ this.online_list = data.data.online_users
+ },
+ },
+ },
+ },
}

Remove mock data

Now that we have the real data, let's remove the mock online user state

<script>
import gql from 'graphql-tag'
const SUBSCRIPTION_ONLINE_USERS = gql`
subscription getOnlineUsers {
online_users(order_by: {user: {name: asc }}) {
id
user {
name
}
}
}
`;
export default {
data() {
return {
online_list: [
- { user: { name: "someUser1" }},
- { user: { name: "someUser2" }}
]
};
},

How does this work?

We are using the apollo object to define the subscription query, which functions similar to queries. The online_users prop gives the result of the real-time data for the query we have made.

Refresh your vue app and see yourself online! Don't be surprised ;) There could be other users online as well.

Awesome! You have completed basic implementations of a GraphQL Query, Mutation and Subscription. Easy isn't it?

Close

Get Started with GraphQL Now

Hasura Cloud gives you a fully managed, production ready GraphQL API as a service to help you build modern apps faster.
Ready to get started?
Start for free on Hasura Cloud or you could contact our sales team for a detailed walk-through on how Hasura may benefit your business.
Stay in the know
Sign up for full access to our community highlights, new features, and occasional baby animal gifs! Oh, and we have a strict no-spam rule. โœŒ๏ธ