Skip to content

Commit 19d5474

Browse files
committed
docs: add useSubscription docs
1 parent 12f363b commit 19d5474

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,57 @@ function TasksWithMutation() {
225225
}
226226
```
227227

228+
## useSubscription
229+
230+
If you are just interested in the last subscription value sent by the
231+
server (e. g. a global indicator showing how many new messages you have in an
232+
instant messenger app) you can use `useSubscription` hook in this form:
233+
234+
```javascript
235+
const NEW_MESSAGES_COUNT_CHANGED_SUBSCRIPTION = gql`
236+
subscription onNewMessagesCountChanged($repoFullName: String!) {
237+
newMessagesCount
238+
}
239+
`;
240+
241+
const NewMessagesIndicator = () => {
242+
const { data, error, loading } = useSubscription(
243+
NEW_MESSAGES_COUNT_CHANGED_SUBSCRIPTION
244+
);
245+
246+
if (loading) {
247+
return <div>Loading...</div>;
248+
};
249+
250+
if (error) {
251+
return <div>Error! {error.message}`</div>;
252+
};
253+
254+
return <div>{data.newMessagesCount} new messages</div>;
255+
}
256+
```
257+
258+
For more advanced use cases, e. g. when you'd like to show a notification
259+
to the user or modify the Apollo cache (e. g. you'd like to show a new comment
260+
on a blog post page for a user visiting it just after it was created) you can
261+
use the `onSubscriptionData` callback:
262+
263+
```javascript
264+
const { data, error, loading } = useSubscription(MY_SUBSCRIPTION, {
265+
variables: {
266+
// ...
267+
},
268+
onSubscriptionData: ({ client, subscriptionData }) => {
269+
// Optional callback which provides you access to the new subscription
270+
// data and the Apollo client. You can use methods of the client to update
271+
// the Apollo cache:
272+
// https://www.apollographql.com/docs/react/advanced/caching.html#direct
273+
}
274+
// ... rest options
275+
});
276+
```
277+
278+
228279
## useApolloClient
229280

230281
```javascript

0 commit comments

Comments
 (0)