GraphQL subscriptions and real-time data.
GraphQL subscriptions:
useSubscription hook from Apollo ClientUse useSubscription for real-time data updates:
Combine initial query with subscription for updates:
A subscription that adds an entity to a list needs one cache update: Apollo writes the new message to the cache itself, but it can't know that the message belongs in Chatroom.messages. Add its reference to the list, and skip it when it's already there. The same message can also arrive from your own mutation or a refetch.
{ __ref: "Message:7" }), so compare ids with readField, not objects.modify changes only a field that is already cached. If no query has fetched messages yet, there's nothing to update, and the query fetches the current list when it runs.GraphQL Cache covers modify, updateQuery, eviction, and when refetchQueries is the better tool.
Subscribe only when needed:
Show the user that live updates stopped, and don't report the error yourself. The shell's Apollo client reports a socket that closed for good once per subscription, and the backend has already reported an error it sent (Who reports an error).
Handle connection drops gracefully:
Render with renderWithApollo from @prepared911/util-testing, as for any Apollo test: queries go to the schema-driven MSW handlers, and the cache, masking, and links are the app's. The mock handlers answer HTTP requests, not WebSocket ones, so give the client a terminating link that sends subscriptions to a test-controlled source and everything else to MSW. Then push results from the test.
id with createPreparedMockHandlers({ mocks }) so both name the same entity.push data includes __typename and id, like a server response; @prepared911/data-gql/factories builds whole objects.findBy… after a push: components re-render on a later tick.For more detailed technical guidance, see these reference files: