Last active
July 17, 2021 17:41
-
-
Save DZuz14/36754cf63b0e15bf9b583755d7ce6a32 to your computer and use it in GitHub Desktop.
h
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 React, { useState } from "react"; | |
const useForm = (formData) => { | |
const [fields, setFieldsState] = useState(formData.fields); | |
const [errors, setErrors] = useState({}) | |
const [success, setSuccess] = useState(false) | |
const setFields = (e) => { | |
const name = e.target.getAttribute("name"); | |
const value = e.target.value; | |
setFieldsState((prev) => | |
prev.map((field) => { | |
if (field.name === name) return { ...field, value }; | |
return field; | |
}) | |
); | |
}; | |
const handleSubmit = (e) => { | |
e.preventDefault(); | |
setErrors({}); | |
const errors = validateFields(fields); | |
if (Object.keys(errors).length > 0) { | |
setErrors(errors); | |
} else { | |
setSuccess(formData.success); | |
} | |
}; | |
return { fields, setFields, errors, success }; | |
}; | |
export default useForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment