1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Write a GraphQL Subscription with React Hooks using Urql

    Ian JonesIan Jones
    graphqlGraphQL

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.

    Discuss

    Discuss