I know this has been asked a lot and in many different ways but I couldn't find something that works for me. The functionality I want in my code is this
const TestApp() => {
const [count, setCount] = useState(null);
const updateAndShowCount = () => {
setCount(count + 1);
// This console.log should be happen after setCount() has completed it's job
console.log(count);
}
}
The function will be called by a button onClick effect. What it currently does is to update count and print the value of count before the update.
I want the button press to update count and immediately "after" print the updated value.
This is a test case for achieving what I want, in my actual project the function will receive a value from an input field and then make a get request using that value (with axios). I am assuming that the answer to this simple test case will work in my case as well, and since this asynchronous behaviour is something I don't quite understand yet I thought it would be sensible to get a grasp of the general concept first.
From what I have gathered though, I think I should mention that useEffect() is already being used for an initial get request, so if your answer involves using that you should assume that I don't know how to add something to useEffect() while retaining it's current functionality.
The current useEffect():
useEffect(() => {
axios.get("mybackend/").then(res) => {
setRequestData(res.data);
});
}, []);
My actual question is in bold for clarity. Any info regarding the situation as a whole is welcome as well. Thanks for reading!
setCountis async or not. It's simply not possible. If you want the new value immediately, use what you pass tosetCount(count + 1).