1

https://codesandbox.io/s/busy-lamport-lfqwt?file=/src/App.js:0-678

Using a state hook

const [loading, _setLoading] = useState(false)

A button needs to be disabled based on the the state above

 return (
        <div className="App">
          <button type="button"
             onClick={handleSubmit}
              disabled={loading}> Send </button>
        </div>
      );

The eventhandler is

 async function handleSubmit(event) {
        setLoading(true)
        console.log(loadingRef.current)

        await setTimeout( () => {} , 3000)
        
        setLoading(false)
        console.log(loadingRef.current)
  }

The button needs to be disabled while setTimeout waits for three seconds

React stores the default loading state in a closure when running the event handler later. So I use a useRef to access current value inside the handler ( not related with what needs to be achieved which is..) how to disable the button for three seconds based on the loading state.

1 Answer 1

3

You have a couple issues here:

  1. setTimeout does not return a Promise, so await isn't delaying execution of your second setLoading call.
  2. You are passing onclick (all lowercase) instead of onClick to <Button>.

Resolving these (and clearing out your ref stuff as you said it wasn't related), you land at this working example (demo):

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [loading, setLoading] = useState(false);

  async function handleSubmit(event) {
    setLoading(true);
    console.log(loading);

    await new Promise((resolve) =>
      setTimeout(() => {
        resolve();
      }, 3000)
    );

    setLoading(false);
    console.log(loading);
  }

  return (
    <div className="App">
      <button type="button" onClick={handleSubmit} disabled={loading}>
        Send
      </button>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.