You are viewing the preview version of this book
Click here for the full version.

Updates to a list over time

Code example

Implementation here.

In this example, the backend implements handling of visitor badges. Each badge is issued with a unique ID when a person arrives to the office. Then the badge tracks how many times it was used and its lifecycle ends when it is returned.

The backend defines a subscription for when badges are issued, used, and returned. Then it also defines a query that returns badges ordered by their last updated time decreasing. Importantly, this query supports the onlyActive argument to fetch only non-returned badges.

The schema implementation:

type Badge {
  id: ID!
  issued_at: AWSDateTime!
  returned_at: AWSDateTime
  last_updated: AWSDateTime!
  use_count: Int!
}

type BadgeConnection {
  items: [Badge!]!
  nextToken: String
}

type Subscription {
  badge: Badge
}

type Query {
  badges(onlyActive: Boolean!, nextToken: String): BadgeConnection!
}

The onlyActive argument for the query is important here because the item fetches are different whether it's for a page load or after a reconnection. The initial fetch needs only the active badges. But then after a reconnection, the client needs to download updates for all badges, even when they are returned in the meantime.

Reconnection fetches only new updates

The ordering of the results is also important. While the initial query fetches all active badges, after reconnection only the updates after the last time the client was up-to-date with the backend needs to be returned. To avoid fetching all badges (an operation that potentially returns a large number of items), the client can fetch only the updates it missed.

Refetch paginates only back to the last good point

Then the client shows an up-to-date list of badges:

The box showing the badges

Implementation

The function we'll write is similar to the previous ones: an observable that emits updates:

updates({
  opened: () => setSubscriptionStatus(true),
  closed: () => setSubscriptionStatus(false),
}).subscribe((updates) => handleUpdate(updates));

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions