-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseDataLoader.mjs
More file actions
40 lines (35 loc) · 1.13 KB
/
useDataLoader.mjs
File metadata and controls
40 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
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
38
39
40
import { useContext, useEffect, useRef, useState } from "react";
import DataCacheContext from "./DataCacheContext.mjs";
import dataLoader from "./dataLoader.mjs";
/**
* The useDataLoader API.
* @kind typedef
* @name UseDataLoaderAPI
* @type {Array}
* @prop {CacheReference} 0 The cache reference.
* @prop {UseDataLoaderLoad} 1 Loads data for this cache reference.
*/
/**
* React hook that returns a cache reference and load function for a specified cache key.
* @kind function
* @name useDataLoader
* @param {CacheKey} key A cache key.
* @returns {UseDataLoaderAPI} The useDataLoader API.
*/
export default function useDataLoader(key) {
const dataCache = useContext(DataCacheContext);
const [reference, setReference] = useState(dataCache.get(key));
const keyRef = useRef(key);
const loadRef = useRef(load);
function load(asyncFn) {
const reference = dataLoader(key, asyncFn, dataCache);
reference.load();
setReference(reference);
}
useEffect(() => {
keyRef.current = key;
loadRef.current = load;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
return [reference, loadRef.current];
}