-
Notifications
You must be signed in to change notification settings - Fork 0
/
useMultiFetch.ts
60 lines (51 loc) · 1.43 KB
/
useMultiFetch.ts
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
import { useState, useEffect } from "react";
import { csvToJson } from "./csvToJson"
import { ChartObject, ChartDataObject } from "../config/charts";
export interface MultiFetchProps {
error: Boolean;
isLoaded: Boolean;
chartData: ChartDataObject[];
}
export const useMultiFetch = (
chart: ChartObject,
startDate: string,
endDate: string
): MultiFetchProps => {
const [chartData, setChartData] = useState<ChartDataObject[]>([]);
const [isLoaded, setIsLoaded] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
setChartData([]);
setIsLoaded(false);
setError(false);
(async () => {
const data = await Promise.all(
chart.data.map(async (datum: ChartDataObject) => {
const realUrl = datum.url
.replace("${startDate}", startDate)
const response = await fetch(realUrl);
const data = await response.text();
const parsedData = csvToJson(data);
return {
...datum,
data: parsedData,
};
})
);
const hasLoaded =
data.length &&
data.reduce(
(acc, curr: ChartDataObject) => acc && !!curr.data?.length,
true
);
setChartData(hasLoaded ? data : []);
setIsLoaded(!!hasLoaded);
setError(!hasLoaded);
})();
}, [chart, startDate, endDate]);
return {
error,
isLoaded,
chartData,
};
};