Created
October 29, 2021 04:56
-
-
Save DarlonHenrique/3a12cf3c90c3832c394442be34c8e92b to your computer and use it in GitHub Desktop.
simple reactive and flexible react form
This file contains 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 from 'react' | |
import useFetch from '../hooks/useFetch' | |
const formFields = [ | |
{ | |
id: 'nome', | |
label: 'Nome', | |
type: 'text' | |
}, | |
{ | |
id: 'email', | |
label: 'Email', | |
type: 'email' | |
}, | |
{ | |
id: 'senha', | |
label: 'Senha', | |
type: 'password' | |
}, | |
{ | |
id: 'cep', | |
label: 'CEP', | |
type: 'text' | |
}, | |
{ | |
id: 'rua', | |
label: 'Rua', | |
type: 'text' | |
}, | |
{ | |
id: 'numero', | |
label: 'Numero', | |
type: 'text' | |
}, | |
{ | |
id: 'bairro', | |
label: 'Bairro', | |
type: 'text' | |
}, | |
{ | |
id: 'cidade', | |
label: 'Cidade', | |
type: 'text' | |
}, | |
{ | |
id: 'estado', | |
label: 'Estado', | |
type: 'text' | |
} | |
] | |
const Form = () => { | |
const { request } = useFetch() | |
const [form, setForm] = React.useState( | |
formFields.reduce((acumulator, field) => { | |
return { | |
...acumulator, | |
[field.id]: '' | |
} | |
}, {}) | |
) | |
async function fetchData() { | |
const { response } = await request( | |
'https://ranekapi.origamid.dev/json/api/usuario', | |
{ | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify(form) | |
} | |
) | |
if (response.status === 200) alert('Cadastro realizado com sucesso!') | |
console.log(response) | |
} | |
function handleChange({ target }) { | |
const { id, value } = target | |
setForm({ ...form, [id]: value }) | |
} | |
function handleSubmit(event) { | |
event.preventDefault() | |
fetchData() | |
} | |
return ( | |
<form onSubmit={handleSubmit}> | |
{formFields.map(({ id, label, type }) => { | |
return ( | |
<div key={id}> | |
<label htmlFor={id}>{label}</label> | |
<input | |
onChange={handleChange} | |
type={type} | |
id={id} | |
value={form[id]} | |
autoComplete='no' | |
/> | |
</div> | |
) | |
})} | |
<button>Cadastrar</button> | |
</form> | |
) | |
} | |
export default Form |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment