Skip to content

Instantly share code, notes, and snippets.

@jourdanmauricio
Created April 26, 2022 12:13
Show Gist options
  • Select an option

  • Save jourdanmauricio/a489c9b7d6b2abe524d6a4c8ed303fdf to your computer and use it in GitHub Desktop.

Select an option

Save jourdanmauricio/a489c9b7d6b2abe524d6a4c8ed303fdf to your computer and use it in GitHub Desktop.
Validación básica de formularios en React.js
import { useState } from "react";
import { helpHttp } from "../helpers/helpHttp";
export const useForm = (initialForm, validateForm) => {
const [form, setForm] = useState(initialForm);
const [errors, setErrors] = useState({});
const [loading, setLoading] = useState(false);
const [response, setResponse] = useState(null);
const handleChange = (e) => {
const { name, value } = e.target;
setForm({
...form,
[name]: value,
});
};
const handleBlur = (e) => {
handleChange(e);
setErrors(validateForm(form));
};
const handleSubmit = (e) => {
e.preventDefault();
setErrors(validateForm(form));
if (Object.keys(errors).length === 0) {
setLoading(true);
helpHttp()
.post("https://formsubmit.co/ajax/[email protected]", {
body: form,
headers: {
"Content-type": "application/json",
Accept: "application/json",
},
})
.then((res) => {
setLoading(false);
setResponse(true);
setForm(initialForm);
setTimeout(() => {
setResponse(false);
}, 5000);
});
} else {
return;
}
};
return {
form,
errors,
loading,
response,
handleChange,
handleBlur,
handleSubmit,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment