Blackfrwhite
Blackfrwhite

Reputation: 49

Disabling submit button when submitting form in React not working as expected when using useState hook

    const [buttonDisabled, setButtonDisabled] = useState(false);

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        setButtonDisabled(true);

        const response = await fetch(
            "http://localhost:5000/....",
            {
                method: "POST",
                body: JSON.stringify(state),
            },
        );
        setButtonDisabled(false);

        const responseJson = await response.text();

    };

// Button 
<button disabled={buttonDisabled} type="submit">Submit form</button>

I expect the button to get disabled (there is an indicator) during the fetching but it's not working. What am I doing wrong? Also is this an appropriate way to handle disabling the button? Or is there a better way.

Upvotes: 1

Views: 5855

Answers (1)

Sam
Sam

Reputation: 1239

Here is the working code. looks like your API is superfast, you are not able to see the difference. https://codesandbox.io/s/competent-hellman-tf346?file=/src/App.tsx:0-817

import * as React from "react";
import "./styles.css";

export default function App() {
  const [buttonDisabled, setButtonDisabled] = React.useState(false);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    console.log("here");
    event.preventDefault();
    setButtonDisabled(true);

    const response = await fetch("http://localhost:5000/....", {
      method: "POST",
      body: JSON.stringify({})
    });
    const responseJson = await response.text();
    setButtonDisabled(false);
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <button disabled={buttonDisabled} type="submit">
          Submit form
        </button>
      </form>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Upvotes: 3

Related Questions