forked from os2display/display-api-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch-data-hook.js
More file actions
83 lines (69 loc) · 2.4 KB
/
Copy pathfetch-data-hook.js
File metadata and controls
83 lines (69 loc) · 2.4 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
function useFetchDataHook(apiCall, ids, params = {}, key = "id") {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const dispatch = useDispatch();
useEffect(() => {
if (!ids || ids.length === 0) return;
// Filter out null/undefined/empty IDs
const validIds = ids.filter((id) => id != null && id !== "");
if (validIds.length === 0) return;
// Check if params contain invalid values
const hasInvalidParams = Object.values(params).some(
(value) => value === "" || value == null,
);
if (hasInvalidParams) return;
async function fetchItems() {
setLoading(true);
try {
let allItems = [];
let fetchedItems = [];
for (const id of validIds) {
let page = 1;
let totalItems = 1; // Will be overridden when we know the total amount.
while (fetchedItems.length < totalItems) {
params[key] = id;
const {
data: {
"hydra:member": items = [],
"hydra:totalItems": hydraTotalItems = 0,
},
originalArgs,
} = await dispatch(
apiCall({
...params,
page,
// The max items per page is 30: https://github.com/os2display/display-api-service/blob/develop/config/packages/api_platform.yaml#L11
itemsPerPage: 30,
}),
);
// We don't like those darn infinite loops.
if (items.length === 0) {
break;
}
// Sometimes we use the arguments from the api call
const itemsWithOriginalArgs = items.map((item) => ({
...item,
originalArgs,
}));
totalItems = hydraTotalItems;
fetchedItems = fetchedItems.concat(itemsWithOriginalArgs);
page++;
}
allItems = allItems.concat(fetchedItems);
fetchedItems = [];
}
setData(allItems);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchItems();
}, [apiCall]); // Should params beadded here to rerun on change?
return { data, loading, error };
}
export default useFetchDataHook;