Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...