Skip to content

Instantly share code, notes, and snippets.

@SergProduction
Created July 29, 2019 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergProduction/a5d084f8a64b53f0f488916187b0f5bf to your computer and use it in GitHub Desktop.
Save SergProduction/a5d084f8a64b53f0f488916187b0f5bf to your computer and use it in GitHub Desktop.
import React, { Fragment, useState, useEffect } from "react"
export const types = {
text: (a) => ({ type: 'text', payload: a }),
password: (a) => ({ type: 'text', payload: a }),
checkbox: (a) => ({ type: 'checkbox', payload: a }),
checkboxGroup: (a) => ({ type: 'checkbox-group', payload: a }),
radio: (a) => ({ type: 'radio', payload: a }),
file: (filename, file) => ({ type: 'file', payload: { filename, file } }),
selectOne: (a) => ({ type: 'select-one', payload: a }),
other: (typeName, a) => ({ type: 'other', payload: a }),
}
export function useForms(initial = {}) {
const [values, setValues] = useState(initial)
// console.log({values})
const onChange = (name) => (event) => {
let data = null
if (!values[name]) {
console.error(`useForm: this name ${name} in not defined in initial`)
return ''
}
const { type } = values[name]
if (type === 'checkbox-group') {
data = types.checkboxGroup(event)
}
else if (event.constructor.name !== 'SyntheticEvent') {
data = types.other(name, event)
}
else if (event.currentTarget.type === 'text' || event.currentTarget.type === 'password') {
data = types.text(event.currentTarget.value)
}
else if (event.currentTarget.type === 'radio') {
data = types.radio(event.currentTarget.value)
}
else if (event.currentTarget.type === 'file') {
data = types.file(event.currentTarget.value, event.currentTarget.files[0])
}
else if (event.currentTarget.type === 'checkbox') {
data = {
type: 'checkbox',
payload: !values[name]
? true
: !values[name].payload
}
}
else if (event.currentTarget.type === 'select-one') {
data = types.selectOne(event.currentTarget.value)
}
else {
console.error(`no detect type form - ${name}`)
console.log(event)
return
}
setValues({
...values,
[name]: data
})
}
const getValue = (name) => {
if (!values[name]) {
console.error(`useForm: this name ${name} in not defined in initial`)
return ''
}
if (values[name].type === 'file') {
return values[name].payload.filename
}
return values[name].payload
}
const onSubmit = (fn) => (event) => {
if (event !== undefined) {
event.preventDefault()
}
const result = Object.keys(values).reduce((acc, key) => ({
...acc,
[key]: values[key] === undefined ? ''
: values[key].type === 'file' ? values[key].payload.file
: values[key].payload
}), {})
fn(result)
}
return { onChange, getValue, onSubmit, setValues }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment