简体   繁体   中英

use callback with useState hook in reactjs

i'm trying to update the user info on my database on the handleChange function every time there is a new change but the problem that im facing is that i have to to wait for the setdata till it finish then updateUserInfo how i can solve that

  const [mydata, setData] = useState({
    user_gender: "",
    user_relationship: "",
    user_birth_day: "",
    user_birth_month: "",
    user_gender_interest: "",
    user_birth_year: "",
    user_interests: {
      dancing: false,
      family: false,
      art: false,
      photography: false,
      friends: false,
      travel: false
    }
  });

const handleChange = event => {
    setData({
      ...mydata,
      [event.target.name]: event.target.value
    });
    async function update() {
      await updateUserInfo(mydata[event.target.name], stableDispatch);
    }
    update();
  };

Call updateUserInfo() as a callback.

You can pass a function as a 2nd parameter to setState() which will automatically be called when the state is set.

useEffect(() => {
  updateUserInfo(mydata[event.target.name], stableDispatch));
}, [mydata]);

The solution here is to copy the state in a variable which you can use to update state and the userInfo

const handleChange = event => {

    const data = {
      ...mydata,
      [event.target.name]: event.target.value
    }
    setData(data);
    async function update() {
      await updateUserInfo(data[event.target.name], stableDispatch);
    }
    update();
  };

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