DEV Community

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

Collapse
_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 (developer.mozilla.org/en-US/docs/W...) 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 (github.com/CodeSeven/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 } = event.target;
    setValues({
      ...values,
      [name]: value
    });
  };


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

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

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

  return {
    handleChange,
    handleSubmit,
    values,
    errors
  };
};

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)

Collapse
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.