Created
April 26, 2022 12:13
-
-
Save jourdanmauricio/a489c9b7d6b2abe524d6a4c8ed303fdf to your computer and use it in GitHub Desktop.
Validación básica de formularios en React.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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