siddhant kumar
siddhant kumar

Reputation: 57

I want to store my firestore value as boolean but it is being stored as string

I have a form in reactjs when i submit it it stores value in firestore database. I have a status feild where users can choose true or false, my problem is this option gets submitted as a string, i want it to get it is submitted as a boolean. Can anyone tell me how to do this.

Code :

const [masterMenu, setMasterMenu] = useState([])
const [form, setForm] = useState({

status: "",

})
const masterMenuCollectionRef = collection(db, "masterMenu")
setForm({
  status: "",
}).then(() => { 
  
 })}
 }
 <div className='outer-container'>
  <h1 className='text-3xl font-bold py-2'>MASTER MENU</h1>
  <label style={{marginLeft: "0.3cm"}}><b>Status</b></label>
      <br />
        <select style={{marginLeft: "0.3cm", marginBottom: "20px", borderBottom: "2px solid 
 #006400", paddingBottom: "10px", width: "38cm"}}
          onChange={e => setForm({ ...form, status: (e.target.valueAsBoolean) })}>
          <option value="">Select Status</option>
          <option value="True">True</option>
          <option value="False">False</option>
        </select>

Upvotes: 0

Views: 725

Answers (2)

PsiKai
PsiKai

Reputation: 1978

You can use JSON.parse to convert it from string to boolean type.

console.log(typeof JSON.parse("false"))
console.log(typeof JSON.parse("true"))

Upvotes: 1

Marc Anthony B
Marc Anthony B

Reputation: 4079

option doesn't accept boolean type of data but there are many ways to convert string into boolean but the most simplest way is to assign the value of True as 1 and False as 0. See example snippet below:

$("#mySelect").change(function() {
  console.log("Selected option is " + $('#mySelect').val());
  console.log(Boolean(parseInt($('#mySelect').val())))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
  <option disabled selected>Select Status</option>
  <option value=1>True</option>
  <option value=0>False</option>
</select>

In the example above, I converted the option value into int by using parseInt and then converting it into Boolean Type. You could also apply this logic into your code and it's up to you how you will implement it.

Upvotes: 1

Related Questions