UNPKG

1.96 kBJavaScriptView Raw
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// flowlint ambiguous-object-type:error
12'use strict';
13
14var _require = require('react'),
15 useCallback = _require.useCallback,
16 useEffect = _require.useEffect,
17 useRef = _require.useRef;
18
19/**
20 * This hook returns a mutable React ref that holds the value of whether a
21 * fetch request is in flight. The reason this is a mutable ref instead of
22 * state is because we don't actually want to trigger an update when this
23 * changes, but instead synchronously keep track of whether the network request
24 * is in flight, for example in order to bail out of a request if one is
25 * already in flight. If this was state, due to the nature of concurrent
26 * updates, this value wouldn't be in sync with when the request is actually
27 * in flight.
28 * The additional functions returned by this Hook can be used to mutate
29 * the ref.
30 */
31function useFetchTrackingRef() {
32 var subscriptionRef = useRef(null);
33 var isFetchingRef = useRef(false);
34 var disposeFetch = useCallback(function () {
35 if (subscriptionRef.current != null) {
36 subscriptionRef.current.unsubscribe();
37 subscriptionRef.current = null;
38 }
39
40 isFetchingRef.current = false;
41 }, []);
42 var startFetch = useCallback(function (subscription) {
43 subscriptionRef.current = subscription;
44 isFetchingRef.current = true;
45 }, []);
46 var completeFetch = useCallback(function () {
47 subscriptionRef.current = null;
48 isFetchingRef.current = false;
49 }, []); // Dipose of ongoing fetch on unmount
50
51 useEffect(function () {
52 return disposeFetch;
53 }, [disposeFetch]);
54 return {
55 isFetchingRef: isFetchingRef,
56 startFetch: startFetch,
57 disposeFetch: disposeFetch,
58 completeFetch: completeFetch
59 };
60}
61
62module.exports = useFetchTrackingRef;
\No newline at end of file