Create Subscription and Render Result
So let's define the graphql subscription to be used.
Open src/GraphQLQueries.re
and add the following code, below everything else:
// GraphQL subscription to get the list of online usersmodule GetOnlineUsers = [%graphql{|subscription getOnlineUsers {online_users(order_by: {user: {name: asc }}) {iduser {name}}}|}];module GetOnlineUsersSubscription = ReasonApollo.CreateSubscription(GetOnlineUsers);
In the above code:
GetOnlineUsers
is a graphql query module built from plain string usinggraphql_ppx
. This is similar to wrapping a subscription string withgql
tag in javascript.GetOnlineUsersSubscription
is a typed React component generated with theGetOnlineUsers
subscription. It is similar to the subscription component inreact-apollo
.
Now, we will wrap the component with GetOnlineUsersSubscription
to render the data from subscription instead of the dummy data. Go to src/online-users/OnlineUsersWrapper.re
, remove the dummy data and wrap the JSX with the Subscription component that we described above:
-let sampleUsers = [- {- id: 1,- name: "User 1"- },- {- id: 2,- name: "User 2"- },- {- id: 3,- name: "User 3"- },- {- id: 4,- name: "User 4"- },-];[@react.component]let make = () => {+ <GraphQLQueries.GetOnlineUsersSubscription>+ ...{+ ({result}) => switch(result) {+ | Loading => <div>{ReasonReact.string("Loading")}</div>+ | Error(error) => {+ Js.log(error);+ <div>{ReasonReact.string("Error")}</div>+ }+ | Data(data) => {- let onlineUsers = Array.map(u => <UserItem user={u}/>, sampleUsers);+ let onlineUsers = data##online_users->Belt.Array.keepMap(x => x##user)+ |> Array.map(u => <UserItem user=u />);- let onlineUsersTitle = "Online users - " ++ string_of_int(Array.length(sampleUsers));+ let onlineUsersTitle = "Online users - " ++ string_of_int(Array.length(data##online_users));<div className="onlineUsersWrapper"><div className="sliderHeader">{ReasonReact.string(onlineUsersTitle)}</div>{ReasonReact.array(onlineUsers)}</div>+ }+ }+ }+ </GraphQLQueries.GetOnlineUsersSubscription>}
How does this work?
We are using a subscription component in the form of <GetOnlineUsers>
which gives render props (similar to <Query>
and <Mutation>
components). The result prop when matched with Data
type, gives the result of the realtime data for the query we have made.
Refresh your react 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.
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs