I have two input fields for an exchange interface. The goal is to update the other according to input (based on exchange rate). User can input in either one.
The problem: if users input 5 and get 500 in the other, then they remove two 0 from 500, it won’t be able to get the state update and return 0.05 in the other.
To make it easier to visualize, i have it in codesandbox. Below is the code.
import "./styles.css";
import React from "react";
export default function App() {
const rate = 100;
const [token, setToken] = React.useState();
const [eth, setEth] = React.useState();
console.log("token", token);
console.log("eth", eth);
return (
<div className="App">
<h1>1 eth = 100 token</h1>
<h2>goal: change one input, the other updates automatically</h2>
<input
placeholder="eth"
value={eth}
onChange={(e) => {
let eth_input = e.target.value;
console.log(eth_input);
setToken(eth_input * rate);
}}
/>
<input
placeholder="token"
value={token}
onChange={(e) => {
let token_input = e.target.value;
console.log(token_input);
setEth(token_input / rate);
}}
/>
</div>
);
}