Firebase integration in React

Today we will learn firebase integration in react. We’ll learn, How to add, retrieve and delete record in firebase. Firebase is a Backend-as-a-Service — BaaS — that started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform. Firebase frees developers to focus crafting fantastic user experiences. You don’t need to manage servers. You don’t need to write APIs. Firebase is your server, your API and your datastore, all written so generically that you can modify it to suit most needs. Yeah, you’ll occasionally need to use other bits of the Google Cloud for your advanced applications. firebase integration in react is verify easly. So let’s get started with the firebase integration in react.

When we’re finished, it will look like this:

Let’s get started

Create React App

It is possible to manually create a React app, but Facebook has created a node module create-react-app to generate a boilerplate version of a React application.

We will use npm to install the create-react-app command line interface (CLI) globally (-g).

Open up your terminal and run the below command

npm install -g create-react-app

Type the below command to create new react app

npm create-react-app hello-world

Run Application

Go inside the project directory and run the npm start command to run the application

cd hello-world

npm start

Install the Firebase Module

To make any type of interaction with the Firebase server you need firebase module. To install it type the below command and hit enter, will install the firebase module

npm i firebase

Creating Firebase Database

Now that our app is set up, we’ll need to create an account and database on Firebase so that we can link up our application to it.

Open the firebase website and click Get Started

Now the firebase will asked you to authenticate with your Google account. Select the account that you’d like this project to be affiliated with, and press OK

This should take you to the Firebase console, which looks something like this:

Click on the Create a project will open a dialog to create new project. like this

Enter the project name and accept the terms and conditions and hit Create Project button, It will create new project.

Now go to the project dashboard page. The dashboard page will looks like this

Here you will see the three option. Since we’ll be building a web app, Select third option`. This will open a popup to create web app that looks like this:

Enter the web app name and click on Register app button, will create web app and will show the some code that looks like this

Since we’ll be importing Firebase into our project using ES6 modules, we won’t need those script tags. That config object is important though: it’s how we authenticate our React application with our Firebase database.

Configure Firebase in our React app

Inside the React project directory, go to the src folder and create a new file named firebase.js. Inside this folder, Copy that whole config object and write the values as shown below:

import firebase from 'firebase'


const config = {
    apiKey: "AIzaSyAluQF1dceN0z-ibQrqSlduEfexUA7DrXw",
    authDomain: "w3path-5b087.firebaseapp.com",
    databaseURL: "https://w3path-5b087.firebaseio.com",
    projectId: "w3path-5b087",
    storageBucket: "",
    messagingSenderId: "1063357243120",
    appId: "1:1063357243120:web:2744a797b0ff6e9f"
};

firebase.initializeApp(config);

export default firebase;

Create Database

After the setup firebase class in React app, click on the Continue to console button will redirect you to the dashboard. Here you will find Database option in the left sidebar. To create database click on Database menu. Database page will looks like this

Click on the Create Database button, will open dialog box. Click on the next will ask for the Cloud Firestore location choose location and hit Done button will create database for you.

One last thing we’ll need to do before we can dive into roughing out our App. We need to temporarily disable authentication requirements on our app so that we can add and remove items without needing to have any kind of user authentication flow.

Choose the Realtime Database, you’ll see a Rules tab. This will cause an object to appear that looks something like this:

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": false,
    ".write": false
  }
}

We need to set .read and .write to both be equal to true, otherwise later, when we try to add data to our database from our application, Firebase won’t let us.

Add HTML markup

Open the App.js file and add the below method

render() {

        return (
        <div className="row mt-5">
            <div className="col-md-6">
                <h2 className="text-left">Firebase Demo</h2>
            </div>
            <div className="col-md-6 text-right">
                <form onSubmit={this.handleSubmit}>
                    <input type="text" name="title" placeholder="Title" onChange={this.handleChange} value={this.state.title} />
                    <button>Add Item</button>
                </form>
            </div>
            <div className="col-md-12">
                <div className="card mt-3">
                    <div className="card-body">                        

                        <table className="table table-border">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th width="10%" className="text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody>                                
                                { (this.state.list.length <1)? (<tr><td className="text-center">No record found</td></tr>) : null }
                                { this.state.list.map( row => {
                                    return  (<tr key={row.key}>
                                        <td >{row.title}</td>
                                        <td className="text-right">
                                            <button type="button" className="btn btn-primary" onClick={() => this.remove(row.id)}>Delete</button>
                                        </td>
                                    </tr>)
                                })}
                            </tbody>
                            
                        </table>
                    </div>
                </div>
            </div>
        </div>
        );
    }

In the above html, We have one form to add new record in the firebase and second list of the added record

Define State

state = {
    title: '',
    list: []
};

Add Item in the database

This method will be able to add the data from the firebase database

handleSubmit = (e) => {
        e.preventDefault();

        const itemsRef = firebase.database().ref('items');

        const item = {
            title: this.state.title,        
        }
        itemsRef.push(item);

        this.setState({
            title : ''
        });
}

Retrieving Items from the database

This method will get the added record and set the state

componentDidMount() {

    const itemsRef = firebase.database().ref('items');
    itemsRef.limitToLast(10).on('value', (snapshot) => {
        let items = snapshot.val();
        let newState = [];
        for (let item in items) {
            newState.unshift({
                id: item,
                title: items[item].title,
            });
        }
        this.setState({
            list: newState
        });
    });
}

The Firebase API offers us an incredibly easy way to not only grab this kind information from our database, but also to update us when new values get added to our database. It accomplishes this using the value custom event listener.

Remove Record

This method will be able to remove the data from the firebase database

remove = (id) => {
   const itemRef = firebase.database().ref(`/items/${id}`);
   itemRef.remove();
}

And finally, we’ll create a handleChange method that receives the event from our inputs, and updates the state

handleChange = (e) => {
   this.setState({
     [e.target.name] : e.target.value
   });
}

After the above changes our component will looks like this

import React, { Component } from 'react';
import firebase from '../Firebasee';


class App extends Component {
    
    state = {
        title: '',
        list: []
    };

componentDidMount() {

    const itemsRef = firebase.database().ref('items');
    itemsRef.limitToLast(10).on('value', (snapshot) => {
        let items = snapshot.val();
        let newState = [];
        for (let item in items) {
            newState.unshift({
                id: item,
                title: items[item].title,
            });
        }
        this.setState({
            list: newState
        });
    });
}

    handleSubmit = (e) => {
        e.preventDefault();

        const itemsRef = firebase.database().ref('items');

        const item = {
            title: this.state.title,        
        }
        itemsRef.push(item);

        this.setState({
            title : ''
        });

    }

    remove = (id) => {
        const itemRef = firebase.database().ref(`/items/${id}`);
        itemRef.remove();
    }

    handleChange = (e) => {
        this.setState({
            [e.target.name] : e.target.value
        });
    }
  
    render() {

        return (
        <div className="row mt-5">
            <div className="col-md-6">
                <h2 className="text-left">Firebase Demo</h2>
            </div>
            <div className="col-md-6 text-right">
                <form onSubmit={this.handleSubmit}>
                    <input type="text" name="title" placeholder="Title" onChange={this.handleChange} value={this.state.title} />
                    <button>Add Item</button>
                </form>
            </div>
            <div className="col-md-12">
                <div className="card mt-3">
                    <div className="card-body">                        

                        <table className="table table-border">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th width="10%" className="text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody>                                
                                { (this.state.list.length <1)? (<tr><td className="text-center">No record found</td></tr>) : null }
                                { this.state.list.map( row => {
                                    return  (<tr key={row.key}>
                                        <td >{row.title}</td>
                                        <td className="text-right">
                                            <button type="button" className="btn btn-primary" onClick={() => this.remove(row.id)}>Delete</button>
                                        </td>
                                    </tr>)
                                })}
                            </tbody>
                            
                        </table>
                    </div>
                </div>
            </div>
        </div>
        );
    }
}
  


export default App;

Running application:

Run application using npm start and you should see firebase demo inside browser. Congrats!! See, it was easy.

Preview

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *