-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetchUniList.tsx
84 lines (75 loc) · 1.98 KB
/
useFetchUniList.tsx
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
84
import { useEffect, useReducer } from 'react';
import formatCSV from '../utils/formatCSV';
import {
FetchUniList,
UniListState,
UniListAction,
} from './types';
import { FETCH_UNI_ACTION_TYPES } from './constants';
const useFetchUniList = ({
uniUrl,
}: FetchUniList) => {
const initialState: UniListState = {
hasError: false,
isLoading: false,
uniList: [],
};
const reducer = (state: UniListState, action: UniListAction) => {
switch (action.type) {
case FETCH_UNI_ACTION_TYPES.ERROR: {
return {
...state,
hasError: true,
isLoading: false,
};
}
case FETCH_UNI_ACTION_TYPES.LOADING: {
return {
...state,
isLoading: true,
};
}
case FETCH_UNI_ACTION_TYPES.RESET: {
return {
...initialState,
};
}
case FETCH_UNI_ACTION_TYPES.SET: {
return {
...state,
hasError: false,
isLoading: false,
uniList: action?.payload ?? [],
};
}
default:
return state;
}
};
const [{ hasError, isLoading, uniList }, dispatch]: [UniListState, React.Dispatch<UniListAction>] = useReducer(reducer, initialState);
useEffect(() => {
dispatch({ type: FETCH_UNI_ACTION_TYPES.LOADING });
const controller = new AbortController();
const signal = controller.signal;
fetch(uniUrl, { signal })
.then(resp => resp.text())
.then(data => {
const formattedList = formatCSV(data);
dispatch({ type: FETCH_UNI_ACTION_TYPES.SET, payload: formattedList });
})
.catch(err => {
dispatch({ type: FETCH_UNI_ACTION_TYPES.ERROR });
console.error(`Something unexpected happened fetching UniList CSV: ${err}`);
});
return () => {
controller.abort();
dispatch({ type: FETCH_UNI_ACTION_TYPES.RESET });
};
}, [uniUrl]);
return {
hasError,
isLoading,
uniList,
};
};
export default useFetchUniList;