I'm using useForm hook in react, and for some reason when I enter values into the form and click on the submit button, the state does not take the values I submitted, but takes the values of empty.
Then, when I enter a second set of values into the form and submit it, the state takes the values of the first submission.
It seems that it always goes "one click behind" (see the console.log at the registerAccount function)
I linked the handleSubmit inside the with the registerAccount function, which should execute the update of the state that keeps the accounts on the very first click.
Am I missing something?
import {useForm} from 'react-hook-form'
const AddAccount = ()=> {
const {register, handleSubmit, formState: { errors }} = useForm()
const [items, setItems] = useState([])
const registerAccount = (data)=> {
setItems([...items, data])
console.log(items)
}
return(
<div>
<div className="grid grid-cols-1 justify-items-center">
<h1 className="text-black font-bold py-2 text-2xl" >Agrega una cuenta</h1>
<form onSubmit={handleSubmit(registerAccount)}>
<table className="table-fixed">
<thead>
<th className="w-1/2 "></th>
<th className="w-1/2 "></th>
</thead>
<tbody>
<tr>
<td><label className="py-1">Alias de la cuenta: </label></td>
<td><input defaultValue="" name="accountAlias" placeholder="Alias"
className= "my-3 border-solid border-2 border-gray-900 py-1 px-3"
{...register("accountAlias", {required: "Introduce el nombre de la cuenta"})}/>
<p className="text-red-500 text-sm">{errors.accountAlias?.message}</p>
</td>
</tr>
<tr>
<td><label className="py-1">Tipo de cuenta: </label></td>
<td><select name="accountType" className= "my-3 border-solid border-2 border-gray-900 py-1 px-3"
{...register("accountType", {required: "Selecciona el tipo de cuenta"})}>
<option value="">Selecciona...</option>
<option value="cuenta de gastos">Cuenta de gastos</option>
<option value="ahorro">Ahorro</option>
<option value="tarjeta de crédito">Tarjeta de crédito</option>
<option value="inversión">Inversión</option>
</select>
<p className="text-red-500 text-sm">{errors.accountType?.message}</p>
</td>
</tr>
<tr>
</tr>
</tbody>
</table>
<button className="bg-blue-500 text-white py-2 px-6 px-2 mt-4">Agregar</button>
</form>
</div>
</div>
)
}
export default AddAccount```