Next.js Discord

Discord Forum

State update updates button too late / not properly

Answered
The Fog from Human Resources posted this in #help-forum
Open in Discord
So im writing a small Login form and my goal is to disable a button when both Username and Password are empty, my issue is that the Button seems to update to late, for example if the password field is filled, and i then enter a character for the username, it will only set the button to active when i type the second character, so it needs n+1 key inputs to update its state

export default function LoginPanel() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loginAvailable, setLoginAvailabe] = useState(false);

  function handleLogin(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    // TODO
  }

  function handleFieldUpdate() {
    setLoginAvailabe(username.trim() !== "" && password.trim() !== "");
  }

  return (
    <div className="">
      <div className="">
        <p className="">Login</p>
        <form onSubmit={handleLogin}>
          <div className="bg-base-200 rounded-md p-3">
            <LoginFormField
              placeholder="Username"
              isSecret={false}
              icon={<UserIcon />}
              onChange={(username) => {
                setUsername(username);
                handleFieldUpdate();
              }}
              value={username}
            />
            <LoginFormField
              placeholder="Password"
              isSecret={true}
              icon={<LockClosedIcon />}
              onChange={(password) => {
                setPassword(password);
                handleFieldUpdate();
              }}
              value={password}
            />
            <div className="">
              <button
                className={`dui-btn dui-btn-primary w-[85%] ${!loginAvailable ? "dui-btn-disabled" : ""}`}
                type="submit"
                disabled={!loginAvailable}
              >
                Login
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}
Answered by Asian black bear
Alternatively don't even use handleFieldUpdate to begin with and instead use an effect that runs the code of handleFieldUpdate whenever username or password change.
View full answer

5 Replies

Asian black bear
Don't make the event handler rely on the state variable and instead pass the entered value into it so that it has the current value right away.
Asian black bear
Alternatively don't even use handleFieldUpdate to begin with and instead use an effect that runs the code of handleFieldUpdate whenever username or password change.
Answer
I'll try it out
that works perfectly, tysm!