Button loading state#

When activating an asynchronous action from a button it is a good UX pattern to give the user feedback as to the loading state, this can easily be done by updating your <Button />s props from a state change like below.

 

import React, { useState, useEffect } from 'react'
import {
  Container,
  Row,
  Col,
  Stack,
  Form,
  Button,
  Alert,
} from 'react-bootstrap'

function simulateNetworkRequest() {
  return new Promise((resolve) => setTimeout(resolve, 2000))
}

function LoadingButton() {
  const [isLoading, setLoading] = useState(false)

  useEffect(() => {
    if (isLoading) {
      simulateNetworkRequest().then(() => {
        setLoading(false)
      })
    }
  }, [isLoading])

  const handleClick = () => setLoading(true)

  return (
    <div className="m-test-wrap">
      <Button
        variant="primary"
        disabled={isLoading}
        onClick={!isLoading ? handleClick : null}
      >
        {isLoading ? 'Loading…' : 'Click to load'}
      </Button>
    </div>
  )
}

export default LoadingButton