1 | 'use strict';
|
2 |
|
3 | const { useContext, useEffect, useRef } = require('react');
|
4 | const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
|
5 | const HYDRATION_TIME_MS = require('./HYDRATION_TIME_MS');
|
6 | const HydrationTimeStampContext = require('./HydrationTimeStampContext');
|
7 | const useCache = require('./useCache');
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | module.exports = function useLoadOnMount(cacheKey, load) {
|
38 | if (typeof cacheKey !== 'string')
|
39 | throw new TypeError(
|
40 | typeof process === 'object' && process.env.NODE_ENV !== 'production'
|
41 | ? 'Argument 1 `cacheKey` must be a string.'
|
42 | : createArgErrorMessageProd(1)
|
43 | );
|
44 |
|
45 | if (typeof load !== 'function')
|
46 | throw new TypeError(
|
47 | typeof process === 'object' && process.env.NODE_ENV !== 'production'
|
48 | ? 'Argument 2 `load` must be a function.'
|
49 | : createArgErrorMessageProd(2)
|
50 | );
|
51 |
|
52 | const cache = useCache();
|
53 | const hydrationTimeStamp = useContext(HydrationTimeStampContext);
|
54 |
|
55 | if (
|
56 |
|
57 | hydrationTimeStamp !== undefined &&
|
58 | typeof hydrationTimeStamp !== 'number'
|
59 | )
|
60 | throw new TypeError('Hydration time stamp context value must be a number.');
|
61 |
|
62 | const startedRef = useRef();
|
63 |
|
64 | useEffect(() => {
|
65 | if (
|
66 |
|
67 | !(
|
68 | startedRef.current &&
|
69 | startedRef.current.cache === cache &&
|
70 | startedRef.current.cacheKey === cacheKey &&
|
71 | startedRef.current.load === load
|
72 | ) &&
|
73 |
|
74 | !(
|
75 | cacheKey in cache.store &&
|
76 |
|
77 |
|
78 | performance.now() - hydrationTimeStamp < HYDRATION_TIME_MS
|
79 | )
|
80 | ) {
|
81 | startedRef.current = {
|
82 | cache,
|
83 | cacheKey,
|
84 | load,
|
85 | };
|
86 |
|
87 | load();
|
88 | }
|
89 | }, [cache, cacheKey, hydrationTimeStamp, load]);
|
90 | };
|