Search code examples
reactjsfirebasegoogle-cloud-firestorewebstormincrement

Store Increment Counter In Firebase Cloud Firestore or Realtime Database


I have this very simple increment counter (see below). I built it with React.js on WebStorm. If you load it, it shows you a 0 and every time you click the button the count increases by 1.

What I am trying to do is to save this number in Firebase. So that the count doesn't get lost every time I close the page. Instead I would like to start with the number of all counts so far and that they are always automatically updated in Firebase (Cloud Firestore or Realtime Database).

Does anyone know how I have to set up the Firebase Storage and how I have to adjust the code? Thanks a lot!

import React from "react";
import './App.css';

class SimpleCountdownTimer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            clicks:0,
            show:true
        };
    }

    IncrementItem = () => {
        this.setState({clicks:this.state.clicks + 1});
    }

    ToggleClick = () => {
        this.setState({show: !this.state.show});
    }


  render() {

  return (

<div>

<button onClick={this.IncrementItem}>Increase!</button>
 
    {this.state.show ? <h2>{this.state.clicks}</h2>:''}

</div>
    );
  }
}

export default SimpleCountdownTimer;

Solution

  • With Firestore, this is easy.

    1. Create a collection
    2. Create a document inside the collection
    3. Add a field to the document, with the variable type "number"

    Then, there are two cases:

    I. EASY: the user doesn't need to be logged-in to increment the counter.

    What you'll need to do is create a server function. The trigger of this function will be an HTTP call. From your web page, you send a simple http call to for example "http://your-function-url/?counter=increment" (using axios, jquery, or even just XHR)

    [ Read here on how to that: https://firebase.google.com/docs/functions/http-events ]

    The function will trigger when you call it. Inside the function, you need to add data to Firestore using the set() method, like this...

    db.collection('YOUR_COLLECTION').doc('YOUR_DOCUMENT_ID').set({
      counter: admin.firestore.FieldValue.increment(1); // "counter" is the name of the field you created, 1 is the number by which to increment the value of the "counter" field
    }, {merge:true}) // merge: true means that your document is not overwritten, only updated.
    .then({
      console.log('succesfully incremented the counter');
      return res.end(); // this is important
    })
    .catch({
      console.error('error incrementing the counter: '+err);
      return res.end();
    });
    

    Documentation on how to create a HTTP function on firebase is pretty extensive, so is everything I said above.

    NOT SO EASY: if you need the user to be logged-in to increment the counter, then you'll need to configure Firebase Auth, then use the Firebase Javascript Web SDK to write to Firestore.

    I hope this helps. Feel free to google anything I just said, it's all fairly well documented. Good luck

    Update: to READ the new value of the counter, you'll need to use a client-side document query (search "document.onSnapshot"). It's a way to get the live value from Firestore and display it on your web page. This also means that the document which has the "counter" field needs to be public or only shown to logged-in users. You configure that access in "Firebase Rules" where you can set it so that a specific document has different permissions than the rest of your database.