1 | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
|
2 |
|
3 | function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
|
4 |
|
5 | import { useEffect, useRef, useState } from 'react';
|
6 | import { useApolloClient } from './ApolloContext';
|
7 | import actHack from './internal/actHack';
|
8 | import { objToKey } from './utils';
|
9 | export function useSubscription(query, _temp) {
|
10 | var _ref = _temp === void 0 ? {} : _temp,
|
11 | onSubscriptionData = _ref.onSubscriptionData,
|
12 | overrideClient = _ref.client,
|
13 | options = _objectWithoutPropertiesLoose(_ref, ["onSubscriptionData", "client"]);
|
14 |
|
15 | var client = useApolloClient(overrideClient);
|
16 | var onSubscriptionDataRef = useRef(null);
|
17 |
|
18 | var _useState = useState({
|
19 | loading: true
|
20 | }),
|
21 | result = _useState[0],
|
22 | setResultBase = _useState[1];
|
23 |
|
24 | onSubscriptionDataRef.current = onSubscriptionData;
|
25 |
|
26 | function setResult(newResult) {
|
27 |
|
28 | actHack(function () {
|
29 | setResultBase(newResult);
|
30 | });
|
31 | }
|
32 |
|
33 | useEffect(function () {
|
34 | if (options.skip === true) {
|
35 | return;
|
36 | }
|
37 |
|
38 | var subscription = client.subscribe(_extends({}, options, {
|
39 | query: query
|
40 | })).subscribe(function (nextResult) {
|
41 | var newResult = {
|
42 | data: nextResult.data,
|
43 | error: undefined,
|
44 | loading: false
|
45 | };
|
46 | setResult(newResult);
|
47 |
|
48 | if (onSubscriptionDataRef.current) {
|
49 | onSubscriptionDataRef.current({
|
50 | client: client,
|
51 | subscriptionData: newResult
|
52 | });
|
53 | }
|
54 | }, function (error) {
|
55 | setResult({
|
56 | loading: false,
|
57 | data: result.data,
|
58 | error: error
|
59 | });
|
60 | });
|
61 | return function () {
|
62 | setResult({
|
63 | loading: true
|
64 | });
|
65 | subscription.unsubscribe();
|
66 | };
|
67 | }, [query, options && objToKey(options)]);
|
68 | return result;
|
69 | } |
\ | No newline at end of file |