Trying to save users clicks on firebase, but isn´t increasing at all
**Firebase rules
{
"rules": {
".read": "now < 1718229600000", // Allow read access only until the specified timestamp
".write": true, // Allow write access only until the specified timestamp
"clickCount": {
".write": true // Allow write access to the clickCount node
},
"lastResetMonth": {
".write": true // Allow write access to the lastResetMonth node
}
}
}
**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Monthly Click Counter</title>
<script
src="https://www.gstatic.com/firebasejs/10.12.0/firebase-app.js"
type="module"
></script>
<script
src="https://www.gstatic.com/firebasejs/10.12.0/firebase-database.js"
type="module"
></script>
</head>
<body>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.0/firebase-app.js";
import {
getDatabase,
ref,
set,
runTransaction,
} from "https://www.gstatic.com/firebasejs/10.12.0/firebase-database.js";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "**************",
authDomain: "**************",
databaseURL:
"**************",
projectId: "**************",
storageBucket: "*************",
messagingSenderId: "**************",
appId: "**************",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
// Define the function to increment click count
window.incrementClickCount = function () {
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
const lastResetMonthRef = ref(database, "lastResetMonth");
runTransaction(lastResetMonthRef, (lastResetMonth) => {
if (lastResetMonth !== currentMonth) {
// If it's a new month, reset click count and update last reset month
return set(ref(database, "clickCount"), 1).then(() => {
console.log("Click count reset to 1");
return currentMonth;
});
} else {
// If it's the same month, increment click count
const clickCountRef = ref(database, "clickCount");
return runTransaction(clickCountRef, (currentClickCount) => {
const newClickCount = (currentClickCount || 0) + 1;
console.log("New click count:", newClickCount);
return newClickCount;
});
}
})
.then(() => {
console.log("Click count updated successfully");
})
.catch((error) => {
console.error("Error updating click count:", error);
});
};
</script>
<!-- Button to increment click count -->
<button onclick="incrementClickCount()">Click me</button>
</body>
</html>