1

Simple and quick question (And yes I google it first, got mislead to phone number verification and other stuff), Anyways! back to the point

Why when I input data and I send it to the database it stores everything as a string even though I have set up the type of that input as a 'number'

Snip of code example

//some code that makes sense (and is working so far except for the data type)

                docRef.set({
                    precio: precio
            })

//Some more code that makes sense as well


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

So basically I send some data to the firebase and it does make a collection if there's none and a document with the data i'm sending, now the issue is that the data is being set up as string and I want it as a number so I can use that value later to do some smart maths I guess.

enter image description here

Full code of the important bits

//Relevant variable
const [precio, setPrecio] = useState("");

// Sending all the data I have gathered to the database 
const register = (e) => {
        e.preventDefault();

        const docId = `${grado} | ${descripcion}`;
        const docRef = db.collection('libros').doc(docId);
        console.log(typeof precio)
        docRef.get().then((doc) => {

            if (doc.exists) 
            {
                window.alert("Ya existe ese libro")
            }
            else {

                docRef.set({
                    materia: materia,
                    descripcion: descripcion,
                    editorial: editorial,
                    grado: grado,
                    precio: precio,
                    id: docRef.id

            }).then((r) => {
                window.alert("Libro agregado")
            })}
    })
}

//The bad boy number that still wants to get printed as a string

<div className = "CrearE_row">
                    <input 
                    onChange = {(e) => {setPrecio(e.target.valueAsNumber);}}
                    
                    type = 'number'
                    pattern = "[0-9]*"
                    required
                    placeholder="Precio"
                    />
                </div>
1
  • use parseInt() or parseFloat() to convert it back to numbers and do math. That would fix it? Commented Sep 17, 2021 at 8:30

2 Answers 2

3

It is most probably because you are actually sending data that is of type String, even if they only content numbers. This is quite classical when you input data via an HTML form.

You can check that with the typeof operator, as follows:

console.log(typeof precio);
docRef.set({
   precio: precio
})

The console will probably print "string". You therefore need to convert the value of precio to a number, for example with parseInt(), parseFloat() or Number().


You can see with the following code that if you pass a number, it is correctly saved in the DB.

const precio = 1234;   // We declare a number
console.log(typeof precio);
docRef.set({
   precio: precio
})

Addendum:

As explained in this SO answer you could also use e.target.valueAsNumber instead of e.target.value.

Sign up to request clarification or add additional context in comments.

4 Comments

I do have const [precio, setPrecio] = useState(""); declared beforehand and I changed what I had before to e.target.valueAsNumber it stills get saved as a string though, so my assumption is that in the end I will have to transform it with parseInt(), parseFloat() or Number(). when I need to use it for "smart maths" am I correct ?
What does console.log(typeof precio);give when you declare it via e.target.valueAsNumber? If you still get strings, yes, converting them to number will do the trick.
well looking directly at the database it says string and after setting up the console log Before sending the data to the database it says string as well. want me to upload full code on the question ? (bit long) can probably just resume to the 2 important parts.
oh, wait I think I find the issue I'm 100% sure it might be I set up in the use state("") should probably leave it on blank state(). Edit: Yup that fix it, thanks for the info didn't know you could set up different type of values in the OnChange , every time I ask questions here I learn something new I'm loving this.
0

Any One still wondering then, I had the same problem with it but use "parseInt()" while sending it to the firebase using addDoc. Hopefully this will clear it. And thanks to Renaud.

1 Comment

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.