1 | /**
|
2 | * Copyright (c) Facebook, Inc. and its affiliates.
|
3 | *
|
4 | * This source code is licensed under the MIT license found in the
|
5 | * LICENSE file in the root directory of this source tree.
|
6 | *
|
7 | * @emails oncall+relay
|
8 | *
|
9 | * @format
|
10 | */
|
11 | ;
|
12 |
|
13 | var _require = require('react'),
|
14 | useCallback = _require.useCallback,
|
15 | useEffect = _require.useEffect,
|
16 | useRef = _require.useRef;
|
17 |
|
18 | /**
|
19 | * This hook returns a mutable React ref that holds the value of whether a
|
20 | * fetch request is in flight. The reason this is a mutable ref instead of
|
21 | * state is because we don't actually want to trigger an update when this
|
22 | * changes, but instead synchronously keep track of whether the network request
|
23 | * is in flight, for example in order to bail out of a request if one is
|
24 | * already in flight. If this was state, due to the nature of concurrent
|
25 | * updates, this value wouldn't be in sync with when the request is actually
|
26 | * in flight.
|
27 | * The additional functions returned by this Hook can be used to mutate
|
28 | * the ref.
|
29 | */
|
30 | function useFetchTrackingRef() {
|
31 | var subscriptionRef = useRef(null);
|
32 | var isFetchingRef = useRef(false);
|
33 | var disposeFetch = useCallback(function () {
|
34 | if (subscriptionRef.current != null) {
|
35 | subscriptionRef.current.unsubscribe();
|
36 | subscriptionRef.current = null;
|
37 | }
|
38 |
|
39 | isFetchingRef.current = false;
|
40 | }, []);
|
41 | var startFetch = useCallback(function (subscription) {
|
42 | // Dispose of fetch subscription in flight before starting a new one
|
43 | disposeFetch();
|
44 | subscriptionRef.current = subscription;
|
45 | isFetchingRef.current = true;
|
46 | }, [disposeFetch]);
|
47 | var completeFetch = useCallback(function () {
|
48 | subscriptionRef.current = null;
|
49 | isFetchingRef.current = false;
|
50 | }, []); // Dipose of ongoing fetch on unmount
|
51 |
|
52 | useEffect(function () {
|
53 | return disposeFetch;
|
54 | }, [disposeFetch]);
|
55 | return {
|
56 | isFetchingRef: isFetchingRef,
|
57 | startFetch: startFetch,
|
58 | disposeFetch: disposeFetch,
|
59 | completeFetch: completeFetch
|
60 | };
|
61 | }
|
62 |
|
63 | module.exports = useFetchTrackingRef; |
\ | No newline at end of file |