2

I have a modal component with a button that makes a async call with axios.

I need to remove onClick action while the call is being made to avoid unwanted clicks.

Something like this but more elegant:

const Modal = ( props ) => {  
  const modal = props.modal
  if (!modal.loading) {
    return (
        <div>
          <button onClick={() => props.updateModal(123)}>123</button>        
        </div>
    );
  }
  else {
    return (
        <div>
          <button>123</button>        
        </div>
    );    
  }
}

const mapStateToProps = state => {
  return {
    modal: state.modal,
  }
}

const mapDispatchToProps = dispatch => {
  return {    
    updateModal(number){      
      dispatch(loadingModal(true));      

      // async call
      return axios.post(
          // async call data
        )
        .then((response) => {
          dispatch(loadingModal(false));          
          dispatch(updateModal(number))
        })
        .catch((error) => {
            console.log("Error");
        }
      )
    }
  };
}

1 Answer 1

3

Instead of conditionally rendering the button with and without onClick you can conditionally take the action like

const Modal = ( props ) => {  
  const modal = props.modal
  const handleClick = (val) => {
       if(!modal.loading) {
          props.updateModal(val)
       }
   }
    return (
        <div>
          <button onClick={() => handleClick(123)}>123</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.