Search code examples
javascriptreactjsasync-awaitsettimeout

React call setTimeout at onClick seems not to wait


I need to execute an async function on onClick function. So, the first step is to simulate it using a setTimeout, I tried but my component doesn't wait 3 seconds. What's wrong with my code? It's very very easy.

const {useState} = React;

const App = ({}) => {
  const [loading, setLoading] = useState(false);

  const doThat = async () => {
    console.log(" doThat");
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 3000);
    setLoading(false);
  };

  return loading ? (
    <div>Loading...</div>
  ) : (
    <div>
      <h1
        onClick={() => {
          console.log("clicked...");
          doThat();
          console.log("...end");
        }}
      >
        Click me
      </h1>
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>


Solution

  • Just remove setLoading(false); after setTimeout

      const doThat = async () => {
        console.log(" doThat");
        setLoading(true);
        setTimeout(() => {
          setLoading(false);
        }, 3000);
      };