Home > Mobile >  Waiting for react state to update in function component
Waiting for react state to update in function component

Time:01-20

How can I make sure that handleOpen only executes after all the states (nameError, emailError, messageError) have been updated? My problem is that since state doesn't update immediately, sometimes handleOpen executes when it shouldn't.

const handleSend = (e) => {
e.preventDefault();
if (name === "") {
  setNameError(true);
}
if (email === "") {
  setEmailError(true);
  setEmailErrorMessage("Please type your email!");
}
if (!email.includes("@")) {
  setEmailError(true);
  setEmailErrorMessage("Invalid email address");
}
if (message === "") {
  setMessageError(true);
}
if (!nameError && !emailError && !messageError) {
  handleOpen();
}

};

CodePudding user response:

You can use react's useRef hook, for its not reactive, i.e doesnt cause page rerender so that you're sure

if (!nameError && !emailError && !messageError) {
  handleOpen();
}

executes when the right in the order you wanted just as i'll show below

const setNameError = useRef(null);
const setEmailError = useRef({value : false, message : ''});
const setMessageError = useRef(null);
const handleSend = (e) => {
e.preventDefault();
if (name === "") {
  setNameError.current = true;
}
if (email === "") {
  setEmailError.current.value = true;
  setEmailError.current.message = "Please type your email!";
}
if (!email.includes("@")) {
  setEmailError.current.value = true;
  setEmailError.current.message = "Invalid email address";
}
if (message === "") {
  setMessageError.current = true;
}
if (!setNameError.current && !setRmailError.current && !setMessageError.current) {
  handleOpen();
}
};

i have used bad naming conversion so as to go with your example, but in real life you wont chose setNameError for a variable name as I've done but maybe you'll do nameError

CodePudding user response:

I would do a whole refactor on how you are handling the errors, but answering your question, you could do just this:

const handleSend = (e) => {
    e.preventDefault();

    const isNameEmpty = name === "";
    const isEmailEmpty = email === "";
    const isEmailAtMissing = !email.includes("@");
    const isMessageEmpty = message === "";

    setNameError(isNameEmpty);
    setEmailError(isEmailEmpty || isEmailAtMissing);
    setEmailErrorMessage(isEmailEmpty ? "Please type your email!" : "Invalid email address");
    setMessageError(isMessageEmpty);

    if ([isNameEmpty, emailError, emailError].some(value => !!value)) {
        handleOpen()
    }
}

If you save the "errors" in variables, then you make sure you are checking the last values you are using in the states.

  •  Tags:  
  • Related