Reduce a GraphQL Subscription Stream into a Collection with urql

Ian Jones
InstructorIan Jones

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 4 months ago

Now that Subscriptions are working within our app, you'll notice that we are receiving individual comments from the Subscription stream that are overwriting each other.

We want all the comments that come in! To handle this, we'll write a handleSubscription function that will reduce all the comments coming in into an array that we can render in the app.

Instructor: [0:00] When I fire a comment, you can see that the mutation fired, and then our subscription picked up the change. It returned a result, and it's in data GitHub IssueCommentEvent and then our comment. Then when we issue another one, we did another event with another comment.

[0:45] As you can notice, we're not getting an array of comments. Each one overwrites the last comment that came in. To deal with this, URQL gives us a handle subscription call back. We can parse the function in here, and all of the events will be handed off to this function so that we can put them into local state and keep track of all of the events that we care about.

[1:16] I'll write a handle subscription function up here, consthandlesubscription. In the first argument, it gives you all of the comments or all of the events that you've seen before. I'm going to call it comments, and then the next argument is the comment event that is currently happening.

[1:51] You can see this is the pattern of a reducer function, the accumulators, the first argument and then the current value is the second argument. Inside of our function, we can do whatever we want, but we just want to return the comments.

[2:14] All the comments that have happened and then the commentevent.github.issuecommentevent.comment. Now, when we go back to our browser, we can see data is undefined. I'll issue another comment.

[2:57] Then, inside of the data, you can see that now we're getting an array. That's because our handle subscription function is returning us this array. When I issue another comment, you can see that now we have two items in our data array.