简体   繁体   中英

Why my type number value gets stored as a string in Firestore?

I honestly do not know why is not working, it doesn't even make sense and it was working before maybe you can spot something I can't.

I'm updating some data to Firebase with a type number but is getting stored as a string even though I'm using an input type number but it doesn't seem to be working for some reason here's the code:

//Firebase set
const [precio, setPrecio] = useState();
const register = (e) => {
       e.preventDefault();
       const docRef = db.collection('productos_AIB').doc(docId);

       docRef.get().then((doc) => {

           if (doc.exists) 
           {
               window.alert("Ya existe ese producto")
           }
           else {
               
               docRef.set({
                   descripcion: descripcion,
                   tipo: tipo,
                   grado: grado,
                   precio: parseFloat(precio).toFixed(2),
                   cantidad: cantidad,
                   necesita: necesita,
                   id: docRef.id
           }).then((r) => {
               window.alert("Producto agregado")
           })}
   })
}

//Input
<input 
onChange = {(e) => {setPrecio(e.target.valueAsNumber);}}
type = 'number'
pattern = "[0-9]*"
requiredplaceholder="Precio"
/>

if you require something else let me know, IDK why it stopped working maybe I changed something without even noticing but I can't spot the error.

UPDATE forgot to add a picture of how it looks in Firestore:

在此处输入图像描述

Probably, the value of "precio" comes from a user input, which most likely it's a literal string, rather than a number. So toFixed() won't provide what you're expecting. To solve this, you should change the following line of code:

precio: parseFloat(precio).toFixed(2),

Into:

precio: parseFloat(parseFloat(precio).toFixed(2)),

In this way, you'll be able to write a number and not a string into Firestore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM