I have an application that displays a list of jobs, each of which can be in one of several statuses (the job status is handled on the GraphQL-Yoga backend and stored in a Prisma DB). I can add jobs, delete jobs, and the job status is changed, as said, on the backend. The front end is built using React Apollo

At the moment I am using a Query component which displays all current jobs with their statuses. I use polling within the Query component to keep the list up to date. I don't have to do anything special if I add or delete a job, or when the backend changes their status. It works great.

 <Query query={this.JOBS_QUERY} pollInterval={500}>

I was thinking, however, that a better solution would be to make use of subscriptions, but I'm unsure how to do this.

My first thought was to set up a subscription for the entire list of jobs and then publish to that subscription from the backend every time I add or delete a job, and whenever the job status is changed. That is, something like this

type Subscription {
    jobs: [Job] !

After looking at the official docs, I was wondering whether the better way to do it was to instead have a subscription that only returns one job

  type Subscription {
        job: Job !

and integrate that into the current display using subscribeToMore, using a pure function to integrate it into the client store. From the page given above, their example is

        subscribeToNewComments={() =>
            document: COMMENTS_SUBSCRIPTION,
            variables: { repoName: params.repoName },
            updateQuery: (prev, { subscriptionData }) => {
              if (!subscriptionData.data) return prev;
              const newFeedItem = subscriptionData.data.commentAdded;

              return Object.assign({}, prev, {
                entry: {
                  comments: [newFeedItem, ...prev.entry.comments]

I'm sure this works well with simply adding a new job (or in this case, comment), but how about deleting the job, or changing its status? Would this not become complicated? Would it in fact be better to maintain a subscription to all the jobs?

If one were to set up a subscription to all jobs, how does one do that? I assume one uses a single Subscription component, which replaces the original Query component? How does one load the list of data on component mount -- that is, before there are any changes published?

tl;dr: When you have a list of data, such as 'jobs' or comments, what is the best way to use the Apollo Client Subscription component to load the data on component mount as well as reflect additions, deletions and changes?

0 Answers