UNPKG

2.69 kBJavaScriptView Raw
1'use strict';
2
3const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
4const useAutoAbortLoad = require('./useAutoAbortLoad');
5const useCacheEntryPrunePrevention = require('./useCacheEntryPrunePrevention');
6const useLoadOnDelete = require('./useLoadOnDelete');
7const useLoadOnMount = require('./useLoadOnMount');
8const useLoadOnStale = require('./useLoadOnStale');
9
10/**
11 * A React hook to prevent a [cache]{@link Cache#store} entry from being pruned
12 * while the component is mounted and automatically keep it loaded. Previous
13 * loading that started via this hook aborts when new loading starts via this
14 * hook, the hook arguments change, or the component unmounts.
15 * @kind function
16 * @name useAutoLoad
17 * @param {CacheKey} cacheKey Cache key.
18 * @param {Loader} load Memoized function that starts the loading.
19 * @returns {Loader} Memoized [loader]{@link Loader} created from the `load` argument, that automatically aborts the last loading when the memoized function changes or the component unmounts.
20 * @see [`useCacheEntryPrunePrevention`]{@link useCacheEntryPrunePrevention}, used by this hook.
21 * @see [`useAutoAbortLoad`]{@link useAutoAbortLoad}, used by this hook.
22 * @see [`useLoadOnMount`]{@link useLoadOnMount}, used by this hook.
23 * @see [`useLoadOnStale`]{@link useLoadOnStale}, used by this hook.
24 * @see [`useLoadOnDelete`]{@link useLoadOnDelete}, used by this hook.
25 * @see [`useWaterfallLoad`]{@link useWaterfallLoad}, often used alongside this hook for SSR loading.
26 * @example <caption>Ways to `import`.</caption>
27 * ```js
28 * import { useAutoLoad } from 'graphql-react';
29 * ```
30 *
31 * ```js
32 * import useAutoLoad from 'graphql-react/public/useAutoLoad.js';
33 * ```
34 * @example <caption>Ways to `require`.</caption>
35 * ```js
36 * const { useAutoLoad } = require('graphql-react');
37 * ```
38 *
39 * ```js
40 * const useAutoLoad = require('graphql-react/public/useAutoLoad');
41 * ```
42 */
43module.exports = function useAutoLoad(cacheKey, load) {
44 if (typeof cacheKey !== 'string')
45 throw new TypeError(
46 typeof process === 'object' && process.env.NODE_ENV !== 'production'
47 ? 'Argument 1 `cacheKey` must be a string.'
48 : createArgErrorMessageProd(1)
49 );
50
51 if (typeof load !== 'function')
52 throw new TypeError(
53 typeof process === 'object' && process.env.NODE_ENV !== 'production'
54 ? 'Argument 2 `load` must be a function.'
55 : createArgErrorMessageProd(2)
56 );
57
58 useCacheEntryPrunePrevention(cacheKey);
59
60 const autoAbortLoad = useAutoAbortLoad(load);
61
62 useLoadOnMount(cacheKey, autoAbortLoad);
63 useLoadOnStale(cacheKey, autoAbortLoad);
64 useLoadOnDelete(cacheKey, autoAbortLoad);
65
66 return autoAbortLoad;
67};