diff --git a/concurrency/public/style.css b/concurrency/public/style.css
index 4e36b11..db6a7ea 100644
--- a/concurrency/public/style.css
+++ b/concurrency/public/style.css
@@ -1,6 +1,7 @@
.grid-container {
display: grid;
grid-template-columns: auto auto;
+
}
div.wrapper{
@@ -10,13 +11,8 @@ div.wrapper{
padding: 10px;
}
-.convert-button {
- position: relative;
- left: auto;
- right: auto;
-}
-
-input + input {
+/* All inputs preceded by another input */
+input + input {
margin-left: 1.5rem;
}
diff --git a/concurrency/src/Exchanger.tsx b/concurrency/src/Exchanger.tsx
index f481f06..05ddf52 100644
--- a/concurrency/src/Exchanger.tsx
+++ b/concurrency/src/Exchanger.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useRef, useState } from "react";
import axios from "axios";
import Rates from "./Rates";
@@ -6,24 +6,25 @@ import Rates from "./Rates";
function Exchanger() {
let [rates, setRates] = useState({} as Rates);
- let [inputOne, setInputOne] = useState("0");
+ let [inputOne, setInputOne] = useState("");
let [selectedOne, setSelectedOne] = useState("USD");
let [selectedTwo, setSelectedTwo] = useState("EUR");
let [result, setResult] = useState("0.00");
+ const isFirstRender = useRef(true);
useEffect(() => {
- let saved = Number(localStorage.getItem("saved"));
+ const saved = Number(localStorage.getItem("saved"));
if (Math.floor(Date.now() / 1000) - saved > 86400) {
// If it's been more tha 24 hours, fetch new rates
// The timeout is 24 hours because that's how often the exchangerate-api refreshes its data
axios.get(process.env.API_URL).then(resp => {
setRates(resp.data);
- localStorage.setItem("saved", Math.floor(Date.now() / 1000).toString());
+ localStorage.setItem("saved", Math.floor(Date.now() / 1000).toString()); // convert milliseconds to seconds
localStorage.setItem("rates", JSON.stringify(resp.data));
});
} else {
// Otherwise, just grab them from localstorage
- let data = JSON.parse(localStorage.getItem("rates"));
+ const data = JSON.parse(localStorage.getItem("rates"));
setRates(data);
}
}, []);
@@ -40,7 +41,13 @@ function Exchanger() {
setSelectedTwo(event.target.value);
}
- function handleConvertClick() {
+ useEffect(() => {
+ if (isFirstRender.current) {
+ // Do nothing if it's the first render
+ // This will ensure this effect will only fire on state updates, not the initial state
+ isFirstRender.current = false;
+ return;
+ }
let inp = Number(inputOne);
if (Number.isNaN(inp)) {
alert("Input must be a number!");
@@ -57,7 +64,7 @@ function Exchanger() {
// Then, convert the USD to the chosen output currency
exchange_rate = rates.conversion_rates[outCurrency];
setResult((usd * exchange_rate).toFixed(2)); // Round to 2 decimal places
- }
+ }, [rates, inputOne, selectedOne, selectedTwo]); // Only run this effect if one of these changed
function handleSwapClick() {
const temp1 = selectedOne;
@@ -72,14 +79,15 @@ function Exchanger() {
if (Object.keys(rates).length) {
return <>