Create Subscription and Render Result

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

Open src/components/OnlineUsers/OnlineUsersWrapper.svelte and add the following code, below the other imports

import OnlineUser from "./OnlineUser.svelte";
+ import { gql } from "@apollo/client";
+ import { subscribe, mutation } from "svelte-apollo";
+ const onlineUsers = subscribe(gql`
+ subscription getOnlineUsers {
+ online_users(order_by: { user: { name: asc } }) {
+ id
+ user {
+ name
+ }
+ }
+ }
+ `);

We are importing the subscribe function from svelte-apollo and passing the graphql subscription query to it. subscribe function returns subscription query results store. You can reference a store value by prefixing the store name with $. So subscription query results can be accessed with $onlineUsers

Add the below code to renders online users

+ {#if $onlineUsers.loading}
+ <div>loading ...</div>
+ {:else if $onlineUsers.error}
+ <div>Error!</div>
+ {:else if $}
+ <div class="onlineUsersWrapper">
+ <div class="sliderHeader">
+ Online users - {$}
+ </div>
+ {#each $ as u (}
+ <OnlineUser user={u.user} />
+ {/each}
+ </div>
+ {/if}

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

Awesome! You have completed implementations of a GraphQL Query, Mutation and Subscriptions.


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. โœŒ๏ธ