Skip to content

Instantly share code, notes, and snippets.

@DZuz14
Last active July 17, 2021 17:41
Show Gist options
  • Save DZuz14/36754cf63b0e15bf9b583755d7ce6a32 to your computer and use it in GitHub Desktop.
Save DZuz14/36754cf63b0e15bf9b583755d7ce6a32 to your computer and use it in GitHub Desktop.
h
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