stackerLoki
stackerLoki

Reputation: 93

How to block double sending when onclick button?

acceptAccess = (item) => {
        const {accept} = this.state;
        let {errors} = this.state;
            if (!isUndefined(accept.text)){
                if (accept.text.length > 0){
                    this.setState({pending: true});//here
                    Global.showSuccessMessage("Задача выполнена");
                    this.setState({postData: {task_guid: this.props.selectedApprove.id, result: item.buttonCode, comment: this.state.accept.text}});
                    setTimeout(
                        function () {
                            DocumentsApi.sendApprove(this.state.postData).then(this.props.onClose());
                        }.bind(this),
                        1000
                    );
                }
            }
        } else  {
            this.setState({pending: true});//here
            Global.showSuccessMessage("Задача выполнена");
            this.setState({postData: {task_guid: this.props.selectedApprove.id, result: item.buttonCode, comment: this.state.accept.text}});
            setTimeout(
                function () {
                    DocumentsApi.sendApprove(this.state.postData).then(this.props.onClose());
                }.bind(this),
                1000
            );
        }
        this.props.update;
    };

Why did pending doesnt help ? and sometimes i have double request? What i need to do for solve this problem?
Who know what to do in this situation ?

Upvotes: 3

Views: 70

Answers (2)

anirudh chauhan
anirudh chauhan

Reputation: 84

You can simply disable the button using the event object till the request on the first click it not fulfilled.

Upvotes: 0

Ivanhoe Cheung
Ivanhoe Cheung

Reputation: 80

You could use lodash throttle to prevent any event triggered more than once

https://lodash.com/docs/4.17.15#throttle

Example:

const clickHandler = _.throttle(e => acceptAccess(e), 1000, { trailing: false });
...
<button onClick={()=>clickHandler(e)}>

Upvotes: 1

Related Questions