-
Notifications
You must be signed in to change notification settings - Fork 2
/
App.jsx
65 lines (55 loc) · 1.62 KB
/
App.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, { useState, useEffect } from "react";
import { updateBalance } from "./api/updateBalance";
import "./App.css";
import BankAccountAction from "./components/BankAccountAction";
function App({ initialBalance = 0 }) {
const [currentBalance, setCurrentBalance] = useState(initialBalance);
const [previousBalance, setPreviousBalance] = useState(initialBalance);
const [requestSuccess, setRequestSuccess] = useState();
const [requestError, setRequestError] = useState();
const resetStatusMessages = () => {
setRequestSuccess(undefined);
setRequestError(undefined);
};
useEffect(() => {
if (currentBalance === previousBalance) return;
resetStatusMessages();
const { request, abortRequest } = updateBalance(currentBalance);
request
.then(({ amount }) => {
setRequestSuccess(`New blance was set to ${amount}!`);
})
.catch(({ message }) => {
setRequestError(message);
setCurrentBalance(previousBalance);
});
return abortRequest;
}, [currentBalance]);
const status = requestError ? (
<p className="error">
<strong>{requestError}</strong>
</p>
) : (
requestSuccess && (
<p className="success">
<strong>{requestSuccess}</strong>
</p>
)
);
return (
<div className="App">
<h1>A very simple bank</h1>
<h2>Your balance is {currentBalance}</h2>
<BankAccountAction
currentBalance={currentBalance}
setCurrentBalance={(amount) => {
setPreviousBalance(currentBalance); // React 18 dev mode workaround
setCurrentBalance((balance) => amount + balance);
}}
onBankInputFormChange={resetStatusMessages}
/>
{status}
</div>
);
}
export default App;