DEV Community

Discussion on: [Solved]Data is sending even if validation requirements are not valid, whats the best way to approach this?

_gerald20 profile image
Gerald Stewart • Edited on

This might not be the optimal solution, but I would check if the return value from the validate function equals 0 in length, I know you are already doing this, but you are doing it after you send the API request. I would also recommend the use of promise chaining ( for handling success and error cases on async functions such as API requests. As for displaying success or error messages, you could set some state variable just like you did with the error messages or what I have commonly used is toastr ( for easy popup notifications.

import { useState, useEffect } from "react";
import axios from 'axios';

const useForm = (callback, validate) => {
  const [values, setValues] = useState({ email: '', name: '', subject: '', description: '' })
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleChange = event => {
    const { name, value } =;
      [name]: value

  const handleSubmit = (event) => {
    setErrors(validate(values)).then((errors) => {
    if(errors.length === 0){
       const {email,name,subject,description} = values;'http://localhost:8080/sendme', {

            text: description
        }).then((res) => {
        console.log('Display your success here!');
        }).catch((e) => {
        console.log('Display your error here!');

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

  return {

export default useForm;

Another solution would be to move the axios.get call to the useState call, after you have validated that errors is equal to 0, not sure what the optimal solution is here

(I haven't checked if this code will run, let me know if it does not work)

andrpaul profile image
AndrPaul Author

Thank you, since I posted this issue I switched to "react-hook-form" which worked like a charm, but I can see was wrong here, and used toastr to display my success message as you said and that saved me a lot of time.