I have this simple React sample app (CodeSandbox):
import { useState } from "react";
import "./styles.css";
export default function App() {
const [someText, setSomeText] = useState<string>("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input
type="text"
value={someText}
onChange={(e) => {
setSomeText(e.target.value);
console.log(someText); // output 1
}}
/>
<button type="button" onClick={() => console.log(someText) // output 2 }>
Hit me!
</button>
</div>
);
}
What I'm trying to understand is: "output 1" isn't is always one character compared to what I have typed into the textbox, while "output 2" is up to date when hitting the button.
How can I make sure someText
is up to date after onChange
- given I have more complex scenarios to handle in onChange
?