/
Calculator.jsx
65 lines (56 loc) · 1.87 KB
/
Calculator.jsx
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
import React, { useReducer } from "react";
import fetchNDilation from "../../lib/fetchNDilation";
import { useWindowContext } from "../WindowContext";
import DilationForm from "./DilationForm";
import Result from "./Result";
const initialState = { isLoading: false, dilation: null, error: null };
function reducer(state, action) {
switch (action.type) {
case "FETCH_START":
return { isLoading: true, dilation: null, error: null };
case "FETCH_OK":
return { isLoading: false, dilation: action.payload, error: null };
case "FETCH_NOT_OK":
return { isLoading: false, dilation: null, error: action.payload };
case "FETCH_ERROR":
return { isLoading: false, dilation: null, error: action.payload };
default:
return state;
}
}
const createOnSubmitHandler = (fetch, dispatch) => async (matrix, degree) => {
try {
dispatch({ type: "FETCH_START" });
const response = await fetchNDilation(fetch, matrix, degree);
const body = await response.json();
if (response.ok) {
dispatch({ type: "FETCH_OK", payload: body.value });
} else {
dispatch({ type: "FETCH_NOT_OK", payload: body });
}
} catch (e) {
dispatch({ type: "FETCH_ERROR", payload: e });
}
};
const Calculator = () => {
const [{ isLoading, dilation, error }, dispatch] = useReducer(
reducer,
initialState
);
const window = useWindowContext();
return (
<div>
<DilationForm
onSubmit={
window && createOnSubmitHandler(window.fetch, dispatch)
}
/>
<Result
isLoading={isLoading}
errorDetails={error}
dilation={dilation}
/>
</div>
);
};
export default Calculator;