Unique Qr-Code generator with React and Firebase


React Example

Firebase is an all-in-one backend as a service provider (BaaS) that provides database, authentication, cloud storage among their many services. In this tutorial, you're going to learn how to use Firebase Real-Time Database service in React application.

You're going to build a simple team list application, where users can add, delete, and edit team member information.


Create your database application

First, you need to create your application in the Firebase console.

Then head over to the Database menu and scroll a bit down into the Choose Real-Time Database section.

React Firebase

Set the security rules to start in test mode.

(this makes your database insecure, but it's okay for the purpose of this tutorial.)


Finally, get the configuration needed to integrate Firebase into your web app.


React Firebase

And put your credential in the config file:


const config = {
  apiKey: "{YOUR KEY}",
  authDomain: "{YOUR KEY}",
  databaseURL: "{YOUR KEY}",
}

export default config;

Setting up your React application


Start your React application with create-react-app

npx create-react-app react-firebase-basic

Then install firebase and Bootstrap (so you can skip writing your own css).

npm i firebase bootstrap

Then you can remove everything from src/ since you don't need most of the boilerplates.


Write the index.js file


This file will serve as React entry point:


import React from 'react';
 import ReactDOM from 'react-dom'; 
import 'bootstrap/dist/css/bootstrap.css';
 import App from './App';  ReactDOM.render(<App />, document.getElementById('root'));

Creating your application


It's time to write your App.js file. Let's initialize our Firebase App in the constructor:


import React from 'react'; 
import Firebase from 'firebase';
 import config from './config'; 
class App extends React.Component {
     constructor(props){ super(props);     
      Firebase.initializeApp(config.firebase);
             this.state = {
       developers: [] 
       }
      } //...
}

Then you can write the logic for getting and saving data: writeUserdata will write our state into the database, while getUserData will create a listener on / path, and on value changes, we will assign snapshot value as state.


writeUserData = () => { 
  Firebase.database().ref('/').set(this.state);
   console.log('DATA SAVED');
 } 

getUserData = () => { 
 let ref = Firebase.database().ref('/');
 ref.on('value', snapshot => {
    const state = snapshot.val(); 
  this.setState(state); 
 });
console.log('DATA RETRIEVED'); 
}

Put these writeUserData and getUserData in componentDidUpdate and componentDidMount respectively.

componentDidMount() {
  this.getUserData();
}

componentDidUpdate(prevProps, prevState) {
  // check on previous state
  // only write when it's different with the new state
  if (prevState !== this.state) {
    this.writeUserData();
  }
}

All that's left is to write the render and handle submit form logic: We will map our developers array from state and put each item in a card component. Each card will have a delete and update button. On delete clicked, we will filter out the specific item, while on update clicked, we will get the item data into the form.

handleSubmit will insert data when uid value is false and update data when it is true. We're using refs to get data from form inputs.


import React from "react";
import "bootstrap/dist/css/bootstrap.css";
import Firebase from "firebase";
import config from "./config";
import { QRious } from 'react-qrious'

class App extends React.Component {
 constructor(props) {
 super(props);
 if (!Firebase.apps.length) {
 Firebase.initializeApp(config);
   }
 this.interval = undefined;
 this.state = {
 developers: [],
 current : {}
    };
  }

 componentDidMount() {
 this.getUserData();
  }

 componentDidUpdate(prevPropsprevState) {
 if (prevState !== this.state) {
 this.writeUserData();
    }
  }

 writeUserData = () => {
 Firebase.database()
      .ref("/")
      .set(this.state.developers);
 console.log("DATA SAVED");
  };

 getUserData = () => {
 let ref = Firebase.database().ref("/");
 ref.on("value", snapshot => {
 const state = snapshot.val();
 console.log(state);
 if(state !== null)
      {
 
 this.setState({developers : state});
 
      }
    });
  };

 uuidv4 = () => {
 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
 var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
 return v.toString(16);
    });
  }

 handleSubmit = event => {
 event.preventDefault();
 let name = this.refs.name.value;
 let role = this.refs.role.value;
 let uid = this.refs.uid.value;
 let uuid = this.uuidv4();
 clearInterval(this.interval)
 if (uid && name && role) {
 const { developers } = this.state;
 const devIndex = developers.findIndex(data => {
 return data.uid === uid;
      });
 developers[devIndex].name = name;
 developers[devIndex].role = role;
 developers[devIndex].uuid = uuid;
 let current = developers[devIndex];
 this.setState({ developers,current });
    } else if (name && role) {
 const uid = new Date().getTime().toString();
 const { developers } = this.state;
 let current = { uid, name, role,uuid }
 developers.push(current);
 this.setState({ developers,current});
    }
 console.log("Interval Started 1")
 this.interval = setInterval(this.updateQR,10000);
 this.refs.name.value = "";
 this.refs.role.value = "";
 this.refs.uid.value = "";
  };

 removeData = developer => {
 const { developers } = this.state;
 const newState = developers.filter(data => {
 return data.uid !== developer.uid;
    });
 let current = this.state.current;
 if(this.state.current.uid === developer.uid){
 current = {}
 clearInterval(this.interval);
 alert("Current selection deleted");
    }
 this.setState({ developers: newState,current, });
  };

 currentData = developer => {
 const { developers } = this.state;
 const devIndex = developers.findIndex(data => {
 return data.uid === developer.uid;
    });
 let current = developers[devIndex];
 console.log(current.uuid)
 if(this.interval){
 clearInterval(this.interval);
    }
 console.log("Interval Started 1")
 this.interval = setInterval(this.updateQR,10000);
 this.setState({ developers,current});
  }

 updateData = developer => {
 //this.state.current.uid = developer.uid;
 this.refs.uid.value = developer.uid;
 this.refs.name.value = developer.name;
 this.refs.role.value = developer.role;
  };

 

 updateQR = () => {
 console.log("current state ---- "+this.state.current);
 if(this.state.current !== {}){
 var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
 var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
 return v.toString(16);
        });

 console.log("Wromg")
 const { developers } = this.state;
 
 if(developers !== undefined){
 const devIndex = developers.findIndex(data => {
 return data.uid === this.state.current.uid;
      });
 console.log(devIndex);
 if(devIndex !== -1){
 developers[devIndex].uuid = uuid;
 let current = developers[devIndex];
 console.log(developers[devIndex].uuid)
 console.log(current.uuid);
 this.setState({ developers,current });
      }
 
 
      }//emptr not
    }
  }

 render() {
 const { developers } = this.state;
 return (
 <React.Fragment>
 <div className="container">
 <div className="row">
 <div className="col-xl-12">
 <h1> Development Team</h1>
 </div>
 </div>
 <div className="row">
 <div className="col-xl-12">
 {developers !== [] ? developers.map(developer => (
 <div
 key={developer.uid}
 className="card float-left"
 style={{ width: "18rem", marginRight: "1rem" }}
 >
 <div className="card-body">
 <h5 className="card-title">{developer.name}</h5>
 <p className="card-text">{developer.role}</p>
 <p className="card-text">{developer.uuid}</p>
 <button
 onClick={() => this.currentData(developer)}
 className="btn btn-link"
 >
                      Make this current selection
 </button>
 <button
 onClick={() => this.removeData(developer)}
 className="btn btn-link"
 >
                      Delete
 </button>
 <button
 onClick={() => this.updateData(developer)}
 className="btn btn-link"
 >
                      Edit
 </button>
 </div>
 </div>
              )) : <div><h1>No Data</h1></div>}
 </div>
 </div>
 <div className="row">
 <div className="col-xl-12">
 <h1>Add new team member here</h1>
 <form onSubmit={this.handleSubmit} >
 <div className="form-row">
 <input type="hidden" ref="uid" />
 <div className="form-group col-md-6">
 <label>Name</label>
 <input
 type="text"
 ref="name"
 className="form-control"
 placeholder="Name"
 />
 </div>
 <div className="form-group col-md-6">
 <label>Role</label>
 <input
 type="text"
 ref="role"
 className="form-control"
 placeholder="Role"
 />
 </div>
 </div>
 <button type="submit" className="btn btn-primary">
                  Save
 </button>
 </form>
 </div>
 </div>
 <div className="row">
 <div className="col-xl-12">
 {this.state.current.uuid} - {this.state.current.name} - {this.state.current.role}<br/>
 {this.state.current.uuid  ? (<QRious value={JSON.stringify(this.state.current)} size="100"/>) : "No Qr"}
 
 </div>
 </div>
 </div>
 </React.Fragment>
    );
  }
}

export default App;



You might wonder is it safe to put Firebase Api key in the config where experienced programmers can easily get it. Actually, it’s okay to put it there because Firebase has security rules that ensures only authenticated users can access your database. I just haven’t setup the security rules in this tutorial. So don't put the code in production environment just yet.

17 views

Subscribe to Our Newsletter

© 2023 by BLIO

  • YouTube
  • Instagram
  • reddit-logo-newnew
  • medium-logo
  • LinkedIn
  • github-logo-new
  • Twitter
  • tiktok-logo-newnew
  • Facebook