-
Notifications
You must be signed in to change notification settings - Fork 0
/
Converter.tsx
70 lines (64 loc) · 2.07 KB
/
Converter.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
import React, { useContext, useState } from 'react';
// import { AppState } from '../../context/AppState';
import { Currency } from '../Currency';
import Button from '../form/Button';
import AppContext from '../../context/app_context';
import axios from 'axios';
import { ActionType } from '../../context/actions';
export const Converter = () => {
const { state, dispatch } = useContext(AppContext);
const [send, set_send] = useState('');
// @ts-ignore
const [_, set_receive] = useState('');
const handle_conversion = async () => {
console.log(state);
if (send && state?.receiving_country && state?.sending_country) {
try {
const response = await axios.get(
`https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${state.sending_country.toLowerCase()}/${state.receiving_country.toLowerCase()}.json`
);
if (
response.data.hasOwnProperty(state.receiving_country.toLowerCase())
) {
// calculate total worth
const total =
parseInt(send) *
Math.round(response.data[state.receiving_country.toLowerCase()]);
// format money
const format = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// dispatch convertion to context
dispatch({
type: ActionType.SET_RECEIVING_AMOUNT,
payload: format,
});
}
} catch (error) {
console.log(error);
}
} else {
console.log('choose please');
}
};
return (
// <AppState>
<div className="w-fit">
<Currency
title={'You send'}
value={send}
on_change={set_send}
read_only={false}
type={'text'}
/>
<div className="h h-10 border-l-2 border-dotted ml-6 bg-slate-800 w-fit"></div>
<Currency
title={'You receive'}
read_only={true}
value={state.receiving_amount.toString()}
type={'text'}
on_change={set_receive}
/>
<Button title={'Convert'} on_click={handle_conversion} />
</div>
// </AppState>
);
};