Hi everyone I have some difficulties increment à number in firestore by using a simple button in Vue js, does someone help?
the goals are: *increase and decrease the value of the number through the firestore by using the Counter collection *hide the button to prevent the spam of it
I also done it but did'nt work:
<html>
<HelloWorld msg="Welcome to Your Vue.js App"/>
<span id="countspan">pleas wait...</span>
<button id="incBtn" disabled>Increase</button>
<button id="decBtn" disabled>Decrease</button>
</html>
<script>
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
let span = document.getElementById('countSpan');
let inc = document.getElementById('incBtn');
let dec = document.getElementById('decBtn');
let countVariable;
window.onload = function(){
const dbRef=ref(db);
get(child(dbRef, 'Counter')).then((snapshot)=>{
countVariable = Number(snapshot.val());
if(this.id=='incBtn') countVariable++;
else countVariable--;
update(ref(db,"/"),{Counter: countVariable});
span.innerHTML = countVariable;
setTimeout(BtnEnable,500);
});
}
inc.addEventListener('click',IncDecCounter);
dec.addEventListener('click',IncDecCounter);
function IncDecCounter(){
BtnDisable();
const dbRef= ref(db);
get(child(dbRef, 'Counter')).then((snapshot)=>{
countVariable = Number(snapshot.val());
span.innerHTML = countVariable;
BtnEnable();
});
}
function BtnEnable(){
inc.disabled=false;
dec.disabled=false;
}
function BtnDisable(){
inc.disabled=true;
dec.disabled=true;
}
</script>
To increment the counter in the database, you can use Firebase's atomic increment operator:
import { ... , increment } from 'firebase/database';
// ...
update(dbRef, { 'Counter': increment(1) });
Decrementing is done as an increment with a negative value:
update(dbRef, { 'Counter': increment(-1) });