In this lesson, we set up our
urql client with GraphQL subscriptions.
Urql doesn't support subscriptions by default. We import the
subscriptionExchange along with
defaultExchanges to pass to our
urql client. Next, we import
subscriptions-transport-ws which takes a websocket URL.
Instructor: [0:00] Here we have an app component that is being wrapped by our URQL provider. We're creating our client and passing our URL of our GraphQL server to our client.
[0:12] To add subscriptions, first you need to yarn add subscriptions-transport-ws. This is the package that will handle the subscription connection for you, we'll be passing it to our client provider. Once you run that command, import it subscription client, subscriptions.
[0:49] Next, we need to create a new subscription client equals new subscription client. Subscription client takes two parameters, the first being the URL that we're passing it, and the second is just options which we'll leave empty.
[1:17] Now we need to pass this subscription client to our client so that URQL knows how to handle subscriptions. Subscriptions aren't added by default so we need to add them ourselves.
[1:31] Create client takes exchanges as a parameter and it's an array. Next, we need to import default exchanges and subscription exchange. We need to spread default exchanges.
[1:55] Then we'll call subscription exchange, which is a function. This function takes an object with a key forward subscription. Forward subscription expects a function which takes operation. This is where we use our subscription client, subscriptionClient.request, then we pass the operation to that request.
[2:39] Now we have our URQL client set up with the correct exchanges to handle a subscription connection. If we head over to our browser and add a comment, we'll notice that it got added here and in the other tab.
[3:02] Let's open our developer tools and head over to the networks tab. When we reload, we'll see on the GraphQL request that we are requesting the WebSocket URL.
[3:16] It returned a 101 switching protocols, which means that the server that we're connecting to successfully switched to the WebSocket protocol. If it returned a 200 that means the server doesn't support WebSockets and it's just returning via the HTTPS protocol.
[3:39] To review, we import subscription client from subscriptions-transport-ws. We then create a subscription client passing in our WebSocket URL. We import default exchanges and subscription exchange from URQL.
[3:59] We pass these exchanges to the exchanges option in create client, spreading default exchanges and passing our subscription client to our subscription exchange.