Reputation: 47
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!
Upvotes: 0
Views: 77
Reputation: 41
i'am not sure that i understood your question completely, but i think the answer is: you should use the callback in your setState, like that:
setCount(count => count + 1)
Upvotes: 0
Reputation: 138267
The solution follows naturally when adding count
to your request (I guess it's some query parameter of some sort), because as you then use count
inside the effect, it is a dependency of the effect, thus whenever the dependency changes, the effect will run again:
useEffect(() => {
axios.get("mybackend?count=" + count).then(res) => {
setRequestData(res.data);
});
}, [count]);
Note that the effect is still missing a cleanup callback, which would cancel an ongoing request, so that when count
changes again while the request is still ongoing, not two requests run at the same time concurrently.
Upvotes: 1