import React, {useState} from "react";
import ReactDOM from "react-dom";
function App() {
const [test, setTest] = useState("red");
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const hello = async () => {
setTest("green");
await sleep(2000);
console.log(test) // prints red
}
return (
<div className="App">
<h1>Test Bed React Code Change B</h1>
<button onClick={hello}> test</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In this minimal example, I would expect console.log(test)
to output "green" but it outputs "red" (on the first button click). I know setTest
is async but it should have time to apply while sleeping for 2 seconds.
I'm sure it's a really basic question but I couldn't find a proper answer.