I have an application where i have a input type number fields with a state.
When the user erases all the characters it gives a NaN error.
What solution to avoid the error when the user empties the price field?
I've tried the following solution below, but when it gets an empty number field, it returns a 0, but unfortanely when the user start typing again the 0 keeps on the left side....
const changePresupuestoObraInput = (e: ChangeEvent<HTMLInputElement>) => {
//here i transform the empty NAN value into a 0
if(isNaN(parseFloat(e.target.value))){
const number = Number(e.target.value);
setEditInputPresupuestoObra(number)
};
//here i parse the e.target.value and set on my state
if(!isNaN(parseFloat(e.target.value))){
const number = parseFloat(e.target.value)
setEditInputPresupuestoObra(number)
};
//here i update my obra.
if (obraInfo) {
setObraInfo({ id: obraInfo.id, name: obraInfo.name, direccion: obraInfo.direccion, presupuesto: editInputPresupuestoObra })
}
}
below the code of my input:
<input type="number" readOnly={readOnlyBoolean} value={editInputPresupuestoObra} onChange={changePresupuestoObraInput} name="presupuestoObra" />
I've searched a lot about NaN but didn't find about this. Any suggestion ?
after searching i could find a solution:
let number = parseInt(e.target.value) || "";
Below i'll put all the code:
const changePresupuestoObraInput = (e: ChangeEvent<HTMLInputElement>) => {
let number = parseInt(e.target.value) || "";
setEditInputPresupuestoObra(number as number);
//here i update my obra.
if (obraInfo) {
setObraInfo({ id: obraInfo.id, name: obraInfo.name, direccion: obraInfo.direccion, presupuesto: editInputPresupuestoObra })
}
}
<input type="number" readOnly={readOnlyBoolean} value={editInputPresupuestoObra} onChange={changePresupuestoObraInput} name="presupuestoObra" />
Doing this way solved the problem and it doesnt show console NaN error anymore. Hope it helps somebody.