djorg83 / react-bootstrap-sweetalert

A React implementation of SweetAlert
https://djorg83.github.io/react-bootstrap-sweetalert/
MIT License
252 stars 55 forks source link

on response of axios #33

Closed iSarahSajjad closed 5 years ago

iSarahSajjad commented 5 years ago

Can i show alert on the response from api? if yes please give a demo.

lokesh1729 commented 5 years ago

Yes, you can, here's an example

this.state={
alert: null
}
raiseLoginSignupErrorAlert = (modalType) => {
        let closefn =
            modalType === "signup"
                ? this.closeSignupModal
                : this.closeLoginModal;
        this.setState({
            alert: (
                <SweetAlert
                    danger
                    confirmBtnText="No Worries!"
                    confirmBtnBsStyle="danger"
                    title="Something bad happened!!!"
                    onConfirm={() => {
                        closefn();
                        this.setState({ alert: null });
                    }}
                >
                    We are regretting for it
                </SweetAlert>
            ),
        });
    };
handleSignup = (event) => {
        event.preventDefault();
axios
            .post(
                "/api/signup",
                {
                    firstName: this.firstName.value,
                    lastName: this.lastName.value,
                    email: this.email.value,
                    password: this.password.value,
                    username: this.userName.value,
                },
                { withCredentials: true },
            )
            .then((res) => {
                if (res.data.status_code === 200) {
                    this.setState({
                        alert: (
                            <SweetAlert
                                success
                                confirmBtnText="Cool!"
                                confirmBtnBsStyle="primary"
                                title="Successfully Signed up!!!"
                                onConfirm={() => {
                                    this.closeSignupModal();
                                    this.setState({ alert: null });
                                }}
                            >
                                Please login now
                            </SweetAlert>
                        ),
                    });
                } else {
                    this.raiseLoginSignupErrorAlert("signup");
                }
            })
            .catch((err) => {
                this.raiseLoginSignupErrorAlert("signup");
            });
}
render() {
return({this.state.alert})
}