Harshana
Harshana

Reputation: 35

Check condition before shows a toast notification in React

I am new to react and I try to submit a form. I validated the form and when I click on submit button a toast notification appears and says successful. But when I put incorrect values to fields of the form and submit the button, the toast notification also appears and says successful. But I want to appear in the toast notification when form validation does not give any error. How can I solve this issue? This is the code that wrote to do this task.

function Forms() {
    const apiUrl = '/addSellerOffer';
    const initialValues = { value: '', expiryDate: '', quantity: '' };
    const [formValues, setFormValues] = useState(initialValues);
    const [formErrors, setFormErrors] = useState({});
    const [isSubmitting, setIsSubmitting] = useState(false);
    const history = useHistory();
    const submitForm = () => {
        const data = { value:formValues.value, expiryDate:formValues.expiryDate, quantity:formValues.quantity};
        axios.post(apiUrl, data)
            .then((result) => {
                clear();
                history.push(`/buyer/viewpostdetails/${id}`);
            });
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormValues({ ...formValues, [name]: value });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        setFormErrors(validate(formValues));
        setIsSubmitting(true);
    };

    const validate = (values) => {
        let errors = {};
        if (!values.value) {
            errors.value = "Cannot be blank";
        }
        if (!values.expiryDate) {
            errors.expiryDate = "Cannot be blank";
        }
        if (!values.quantity) {
            errors.quantity = "Cannot be blank";
        }
        return errors;
    };

    useEffect(() => {
        if (Object.keys(formErrors).length === 0 && isSubmitting) {
            submitForm();
        }
    }, [formErrors]);

    const clear = () => {
        setFormValues({ value: '', expiryDate: '', quantity: ''});
    };

    const { id } = useParams();
    console.log(id);

    return(
        <div className="forms-b">
            <div className="forms__container-b" >
                <div className="container-b">
                    <div className="content-b">
                        <form className="buyer-form-b" onSubmit={handleSubmit} noValidate>
                            <div className="user-details-b">
                                <div className="input-box-b">
                                    <span className="details-b">Offer Value</span>
                                    <input type="text" name="value" id="value" placeholder="Enter value" value={formValues.value}
                                           onChange={handleChange}
                                           className={formErrors.value && "input-error"}></input>
                                    {formErrors.value && (
                                        <span className="error" style={{color:'red'}}>{formErrors.value}</span>
                                    )}
                                </div>
                                <div className="input-box-b">
                                    <span className="details-b">Expiry Date</span>
                                    <input type="date" name="expiryDate" id="expiryDate" placeholder="Enter date" value={formValues.expiryDate}
                                           onChange={handleChange}
                                           className={formErrors.expiryDate && "input-error"}></input>
                                    {formErrors.expiryDate && (
                                        <span className="error" style={{color:'red'}}>{formErrors.expiryDate}</span>
                                    )}
                                </div>
                                <div className="input-box-b">
                                    <span className="details-b">Quantity</span>
                                    <input type="text" name="quantity" id="quantity" placeholder="Enter quantity" value={formValues.quantity}
                                           onChange={handleChange}
                                           className={formErrors.quantity && "input-error"}></input>
                                    {formErrors.quantity && (
                                        <span className="error" style={{color:'red'}} >{formErrors.quantity}</span>
                                    )}
                                </div>
                            </div>
                            <div className="button-b">
                                <input onClick={() =>
                                    toast.info("You're added offer successfully !", {
                                        transition: Slide
                                    })
                                } type="submit" value="Send Offer"></input>
                                <ToastContainer position="top-right" toastStyle={{ backgroundColor: "green" }} autoClose={3000} />
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Forms;

Upvotes: 0

Views: 1994

Answers (1)

Gagan
Gagan

Reputation: 318

The problem with your code is that you have added the toast.info action to your submit button unconditionally. You should move that part to the part where the form is actually being submitted i.e the submitForm function. So remove the toast.info part from the input onClick and add it to the submitForm function like this

 const submitForm = () => {
        const data = { value:formValues.value, expiryDate:formValues.expiryDate, quantity:formValues.quantity};
        axios.post(apiUrl, data)
            .then((result) => {
                toast.info("You're added offer successfully !", { transition: Slide})
                clear();
                history.push(`/buyer/viewpostdetails/${id}`);
            });
    };

Upvotes: 1

Related Questions