Estoy tratando de verificar que los campos obligatorios no estén vacíos y me aseguro de que el tipo de entrada sea correcto.
const CreateSensor = () => { const [deveui, setDeveui] = useState(''); const [location, setLocation] = useState(''); const [levelid, setLevel] = useState(''); const submitValue = () => { let data = {deveui,location,levelid}; //POST method fetch("api") ClearFields(); } function ClearFields(){ document.getElementById("dev").value = ""; document.getElementById("location").value = ""; document.getElementById("level").value = ""; } return( <> <hr/> <input type="text" id="dev" placeholder="deveui" onChange={e => setDeveui(e.target.value)} /> <input type="text" id="location"placeholder="Location" onChange={e => setLocation(e.target.value)} /> <input type="text" id="level" placeholder="Levelid" onChange={e => setLevel(e.target.value)} /> <button onClick={submitValue}>Submit</button> </> ) }el botón enviar comprobará si deveui no está vacío y el levelid está establecido en un número entero. He intentado cambiar el tipo de entrada para levelid a números, pero hay flechas que creo que son innecesarias.
Recomiendo encarecidamente usar una biblioteca de formularios React. Aquí hay un ejemplo con forma de gancho de reacción
import { useForm } from "react-hook-form"; const CreateSensor = () => { const { register, handleSubmit, watch, reset, formState: { errors }, } = useForm({ defaultValues: { deveui: "", location: "", levelid: "" } }); const submitValue = ({deveui, location, levelid}) => { // exclude 'deveui' from fetch payload const payload = { location, levelid } // POST data to api, for example fetch("https://myapi.com", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), // reset form state }).then((response) => reset()); }; return ( <> <hr /> <form onSubmit={handleSubmit(submitValue)}> <input {...register("deveui", { required: true })} type="text" id="dev" placeholder="deveui" /> <input {...register("location", { required: true })} type="text" id="location" placeholder="Location" /> <input {...register("levelid", { required: true })} type="text" id="level" placeholder="Levelid" /> <button type="submit">Submit</button> </form> </> ); }