Renan Fernandes
Renan Fernandes

Reputation: 49

how to change the button's loading state only if it was clicked?

I have two buttons that use the same loading condition, but I keep clicking on one, the other also changes the status to loading. How can I solve this?

 const { isLoading } = useRespondConsent();

<ButtonPrimary isLoading={isLoading} onClick={() => handleRespond(true)}>
   Send
</ButtonPrimary>

<Button isLoading={isLoading} onClick={() => handleRespond(false)}>
   Not send
</Button>

Upvotes: 1

Views: 1238

Answers (1)

Andy
Andy

Reputation: 63550

  1. Identify your buttons somehow - with an id or a data-attribute.

  2. Initialise your state as an object.

  3. Two functions. The first to handle the state update when a button is clicked. The second to determine whether a button isLoading. In this example (for convenience) if the button is "loading" it gets disabled.

const { useState } = React;

function Example() {

  // Initialise state with an empty object
  const [ buttonState, setButtonState ] = useState({});

  function handleButton(e) {

    // Grab the id from the button's dataset
    const { id } = e.target.dataset;

    // Preserve the existing state, and
    // update the value of the property identified
    // by the id
    setButtonState({
      ...buttonState,
      [id]: !buttonState[id]
    });
  }

  // Takes an ide and returns the value
  // of the property identified by the id, or false
  function isLoading(id) {
    return buttonState[id] || false;
  }

  return (
    <div>
      <Button
        id="send"
        isLoading={isLoading('send')}
        handleButton={handleButton}
      >Send
      </Button>
      <Button
        id="notsend"
        isLoading={isLoading('notsend')}
        handleButton={handleButton}
      >Not send
      </Button>
    </div>
  );
};

function Button(props) {

  const {
    id,
    isLoading,
    handleButton,
    children
  } = props;

  // Disable the button if isLoading
  // is true
  return (
    <button
      data-id={id}
      disabled={isLoading}
      onClick={handleButton}
    >{children}
    </button>
  );

}

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

Upvotes: 2

Related Questions