Write a GraphQL Subscription with React Hooks using Urql

Ian Jones
InstructorIan Jones

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

In this lesson, we use urql's useSubscription hook to subscribe to a GraphQL subscription.

We write a GraphQL subscription query and pass it to useSubscritpion which returns the result of the subscription we pass it.

Instructor: [00:01] Here, we have a React app that's set up with URQL to handle subscriptions. Over in our app component, we will import useSubscription from URQL. Here, we will call useSubscription. useSubscription takes an object with a property of query.

[00:32] We'll call our query commentSubscriptionQuery. The second parameter is the variables that will be passed to our query, so variables. We will want to pass course slug to our query. useSubscription returns a result in an array, const.

[01:05] Up above, we will define our commentSubscriptionQuery, and it's just a string. It takes a course slug, and it's a string. It's required. We pass the query that we want to subscribe to. In this case, it's comment where course slug is equal to our course slug variable.

[02:02] Next, we'll grab the text off of the comment. Down below, our comments list takes a comments prop, which we will get off of resData.comments, a result. Here, it blows up, because the first time that our app component renders, data is undefined.

[02:36] We need to guard against this. We can do this by going if result.data equals undefined, then we'll return div, no comments. Now, we'll see that everything's rendered correctly, and when we add a comment, we see that it gets added.

[03:14] In our other tab, it's also added. If we add one here, our other tab gets updated correctly, because of the subscription. If we open up our developer tools and head over to the networks tab, when we reload and look at the GraphQL request, we'll see that we get a 101 switching protocols status code.

[03:43] This means that our application has successfully connected to our web socket server. If the status was 200, that means that the server does not accept a web socket connection. To review, we import useSubscription from URQL.

[04:04] We call useSubscription. useSubscription takes an object with a property of query and variables. Our query is a subscription GraphQL query. It returns a result, and we pass our result to our comment list, and everything gets rendered.