JSFiddle - React, Tailwind, and code Playground

by Icesofty

HTML

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./js/click-counter.js" defer></script>
    <title>Firebase & JS</title>
  </head>
  <body>
  

    <button id="btn" style="margin-top: 5rem;">
      CLick Me!
    </button>
    <h2 id="counter"></h2>
      <a href="https://icesofty.github.io/JS-Click-Counter/index.html">Original Version here</a>
  </body>
</html>

JavaScript

const btn = document.getElementById("btn");
const counterID = document.getElementById("counter");

const firebase = "https://my-counter-5a9a7.firebaseio.com/";

let counter;

function get() {
  axios.get(firebase + "my-online-counter.json").then((response) => {
    counter = response.data.counter;
    updateCounter();
  });
}

function updateCounter() {
  counterID.innerHTML = `${counter} visitors clicked on this button`;
}

// Everytime a user click on the button,
//we need to Update the counter into the database
btn.addEventListener("click", function (e) {
  axios
    .put(firebase + "my-online-counter.json", {
      // we indrement the counter, into the DB, by one.
      counter: counter + 1
    })
    .then(() => {
      // Once it's done, we call the get() function again.
      get();
    })
    // If there is an error, we can log it.
    .catch((error) => console.log(error));
});

get();