Joe Essey
Joe Essey

Reputation: 3527

Disable and re-enable button on single action

I need to disable and re-enable a button during the async call. I am only able to disable it. If I add code to re-enable it is ignored. I acknowledge I may not be asking the right question.

I have a function with a button "Action":

<button className={`doFoo${buttonClasses[type]} ${type}`} onClick={onClick} disabled={isButtonDisabled}>

That is called by a React class "Actions":

<Action type="like" onClick={onLike} isButtonDisabled={isButtonDisabled} />

That is called by another React class "List":

<Actions onLike={this.handleLike} onDislike={this.handleDislike} isButtonDisabled={isButtonDisabled}/>

Also in that class is are the following functions:

...
thumbsUp() {
    const {
      ...
    } = this.props;
    const {
      ...
    } = this.state;

    this.setState({ wasLiked: true, viewProfile: false }, () => {
      setTimeout(doThumbsUp, ACTION_CONFIRMATION_ANIMATION_TIMEOUT);
    });

    function doThumbsUp() {
      thumbsUp({
        index: activeIndex,
        id: profiles[activeIndex].id
      });
    }
  },

  handleLike() {
    const { showThumbsUpConfirmation } = this.props;

    if (showThumbsUpConfirmation) {
      this.showThumbsUpConfirmationModal();
    } else {
      this.thumbsUp();
    }
  },
...

Here's what the source looks like:

export function thumbsUp({ id, ... }) {
  return api.post(`${API.ENDPOINTS.FOO}/${id}/thumbs_up`, {
   ...
  });
}

I can place this.setState(isButtonDisabled: true) at various places in this code and that value makes it to the view and disables the button. However I cannot figure out how to re-enable the button after the work has been done.

Upvotes: 0

Views: 158

Answers (1)

finalfreq
finalfreq

Reputation: 6980

If I'm understanding you correctly you want the button to be disabled during async and after async be enabled? If that is the case, wherever you are calling the function that makes the api call, you just need to chain a .then(() => this.setState(isButtonDisabled: false) and that will update the state as soon as response has been received from api call. also if you aren't using es6 just make sure to set this to a variable above the api call to ensure its scoped properly for setState

Upvotes: 0

Related Questions