Why Do I Need To Wrap Setstate Callback In An Anonymous Arrow Function For It To Run After State Change?
Solution 1:
What is confusing you is the order of evaluation in JavaScript, it's nothing React-specific.
If you have
foo(this.doSearch())
doSearch
will be called immediately. That is, even beforefoo
is called, and then the result of doSearch
will be passed to foo
.
You don't want that, you want to pass the computation to the setState
function. That is, you want to pass the functiondoSearch
, not the result of the function.
So what you actually want is
changePage = (e) => {
this.setState({
searchPage: e,
isLoading: true
}, this.doSearch);
}
Which means you're passing the functionthis.doSearch
to setState
. Of course, this.doSearch
is equivalent to () => this.doSearch()
(both are functions that, when called, call this.doSearch()
).
Solution 2:
One calls it immediately and passes its return value as the callback to be used (bad). The other creates a function and that is used as the callback (good).
Its like accidentally writing an event listener like this:
// Assign console.log as the callbak// Will print the event argument on click// (just mentioning for completeness)addEventlistener("click", console.log)
// vs// Immediately print "a"// Add undefined as callback// (your first example [bad])addEventlistener("click", console.log("a")):
// vs// Add function that will print "a" after a click// (your second example [good])addEventlistener("click", () =>console.log("a"))
Post a Comment for "Why Do I Need To Wrap Setstate Callback In An Anonymous Arrow Function For It To Run After State Change?"