This repository was archived by the owner on Jan 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathindex.js
109 lines (100 loc) · 2.6 KB
/
index.js
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import api from "../api/api";
import { Server } from "../utils/config";
import { useEffect, useReducer } from "react";
export const FetchState = {
FETCH_INIT: 0,
FETCH_SUCCESS: 1,
FETCH_FAILURE: 2,
};
export const useGetTodos = (stale) => {
const reducer = (state, action) => {
switch (action.type) {
case FetchState.FETCH_INIT:
return { ...state, isLoading: true, isError: false };
case FetchState.FETCH_SUCCESS:
return {
...state,
isLoading: false,
isError: false,
todos: action.payload,
};
case FetchState.FETCH_FAILURE:
return { ...state, isLoading: false, isError: true };
default:
throw new Error();
}
};
const [state, dispatch] = useReducer(reducer, {
isLoading: false,
isError: false,
todos: [],
});
useEffect(() => {
let didCancel = false;
const getTodos = async () => {
dispatch({ type: FetchState.FETCH_INIT });
try {
const data = await api.listDocuments(Server.collectionID);
if (!didCancel) {
dispatch({ type: FetchState.FETCH_SUCCESS, payload: data.documents });
}
} catch (e) {
if (!didCancel) {
dispatch({ type: FetchState.FETCH_FAILURE });
}
}
};
getTodos();
return () => (didCancel = true);
}, [stale]);
return [state];
};
export const useGetUser = () => {
const reducer = (state, action) => {
switch (action.type) {
case FetchState.FETCH_INIT:
return { ...state, isLoading: true, isError: false };
case FetchState.FETCH_SUCCESS:
return {
...state,
isLoading: false,
isError: false,
user: action.payload,
};
case FetchState.FETCH_FAILURE:
return {
...state,
isLoading: false,
isError: true,
errorMessage: action.payload?.message,
};
default:
throw new Error();
}
};
const [state, dispatch] = useReducer(reducer, {
isLoading: false,
isError: true,
errorMessage: null,
data: [],
});
useEffect(() => {
let didCancel = false;
const getTodos = async () => {
dispatch({ type: FetchState.FETCH_INIT });
try {
const account = await api.getAccount();
if (!didCancel) {
dispatch({ type: FetchState.FETCH_SUCCESS, payload: account });
}
} catch (e) {
if (!didCancel) {
dispatch({ type: FetchState.FETCH_FAILURE });
}
}
};
getTodos();
return () => (didCancel = true);
}, []);
return [state, dispatch];
};