简体   繁体   中英

Using React State Hook, call function after setting multiple states

I'm trying to make a function that will reset multiple states and then make an API call, however I'm having trouble making the API call happen AFTER the three states have been set. My function looks like this:

const resetFilters = () => {
    setYearFilter("");
    setProgressFilter("");
    setSearchFilter("");
    callAPI();
  };

I've tried using Promise.resolve().then() , and tried using async await , but it seems the useState setter function doesn't return a promise. Is there a way to make this all happen synchronously?

You could use useEffect to listen on changes and do each task sequentially

const resetFilters = () => {
  setYearFilter("")
}

useEffect(() => {
  setProgressFilter("")
}, [yearFilter])

useEffect(() => {
  setSearchFilter("")
}, [progressFilter])

useEffect(() => {
  callAPI()
}, [searchFilter])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM