Firebase Tutorial – AppDividend https://appdividend.com Latest Code Tutorials Wed, 31 Oct 2018 22:16:12 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Firebase Tutorial – AppDividend https://appdividend.com 32 32 Laravel Firebase Tutorial https://appdividend.com/2018/04/18/laravel-firebase-tutorial/ https://appdividend.com/2018/04/18/laravel-firebase-tutorial/#comments Wed, 18 Apr 2018 12:16:11 +0000 http://localhost/appdividend/?p=2302 Laravel Firebase Example

Laravel Firebase Tutorial is the topic, we will discuss today. Firebase was established in 2012 as a real-time architecture for synchronizing data between apps. It was taken by Google in 2014. It was a part of a real-time chat integration API. In this example, I will demonstrate how to connect Firebase Real-time Database with Laravel 5.6. We will add […]

The post Laravel Firebase Tutorial appeared first on AppDividend.

]]>
Laravel Firebase Example

Laravel Firebase Tutorial is the topic, we will discuss today. Firebase was established in 2012 as a real-time architecture for synchronizing data between apps. It was taken by Google in 2014. It was a part of a real-time chat integration API. In this example, I will demonstrate how to connect Firebase Real-time Database with Laravel 5.6. We will add the data to the Firebase service. I will write the complete Laravel Firebase CRUD Tutorial post in the future.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

Prerequisites:

  • Laravel 5.6
  • PHP 7.1
  • Google Firebase Real-time Database
  • Web server (Apache, NGINX or integrated PHP web server for testing).

Laravel Firebase Tutorial

First, we install new Laravel Project.

Step 1: Install Laravel Project

composer create-project --prefer-dist laravel/laravel laravelfirebase

Step 2: Install Dependencies

Open your terminal and enter the following command.

composer require kreait/firebase-php ^4.0

Step 3: Setup Firebase

Let’s begin with signing up for a Gmail account. First, Open Google Firebase Console by click on this link Google Firebase Console.Looks like below image.

Laravel Firebase Example

Next window, build a database project and provide information including project name. When finished, click the Create Project button.

Firebase Create Project

Wait for the project to be created and then continue. You will be automatically switched to the Firebase Dashboard.

Firebase Login

After successfully building the project, move to the Database tab, tick Rules to update read and write rules to true and then press the Publish button.

Firebase Database Read Write Access

 Step 4: Generate API Key

How to generate Firebase API key

Firebase makes an  API key for your project.Go to Project settings >>  SERVICE ACCOUNTS.

Laravel 5.6

You can download and paste into app >>  Http >> Controllers.

Step 5: Create Controller

php artisan make:controller FirebaseController --resource

It will create one controller file called FirebaseController.php.

Add the following code to the FirebaseController.php file.

//FirebaseController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

class FirebaseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/laravelfirebase-9d875-firebase-adminsdk-wltre-a1b8486a6c.json');
        $firebase = (new Factory)
        ->withServiceAccount($serviceAccount)
        ->withDatabaseUri('https://laravelfirebase-9d875.firebaseio.com/')
        ->create();

        $database = $firebase->getDatabase();

        $newPost = $database
        ->getReference('blog/posts')
        ->push([
        'title' => 'Laravel FireBase Tutorial' ,
        'category' => 'Laravel'
        ]);
        echo '<pre>';
        print_r($newPost->getvalue());
    }

}

Step 6: Add Route

Next step, We need to define the route in routes  >>  web.php file. So let us do it.

Route::get('firebase','FirebaseController@index');

Start Development Server by typing following command in terminal

php artisan serve

Go to this URL: http://localhost:8000/firebase

Array of data

Laravel 5.6 Firebase Example Tutorial

 Finally, Our Laravel Firebase Tutorial is over. Thanks for taking.

The post Laravel Firebase Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/04/18/laravel-firebase-tutorial/feed/ 3
Angular Firebase Tutorial With Example From Scratch https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/ https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/#comments Fri, 26 Jan 2018 13:38:14 +0000 http://localhost/appdividend/?p=1568 Angular Firebase Tutorial

Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial Example, Angular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From […]

The post Angular Firebase Tutorial With Example From Scratch appeared first on AppDividend.

]]>
Angular Firebase Tutorial

Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial ExampleAngular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From Scratch. We will build Stock Market Application where the user can insert and display the share price from the Firebase.  It is just a skeleton that demonstrates how to do a most common operation with Angular and Firebase. Firebase used a NoSQL Database.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular Firebase Tutorial

As we know, Angular uses TypeScript Language, which is a superset of Javascript. It transpiles the TypeScript code into the Javascript code with the help of webpack. We will start by installing Angular and configure the Firebase with Angular and build the Angular Firebase Project.

Step 1: Install the Angular.

You need to set up a dev environment before you can do anything. Install Node.js® and npm if they are not already on your machine.Then install the Angular CLI globally.

npm install -g @angular/cli

Step 2. Create a new project.

Type the following command. It will create the folder structure and also install the remaining dependencies.

ng new ng5firebase

Step 3: Install Angular Firebase Module.

Hit the following command in the terminal.

npm install firebase angularfire2 --save

Step 4: Add Firebase config to environment variable.

Open /src/environments/environment.ts and add your Firebase configuration:

// environment.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: '<your-key>',
    authDomain: '<your-project-authdomain>',
    databaseURL: '<your-database-URL>',
    projectId: '<your-project-id>',
    storageBucket: '<your-storage-bucket>',
    messagingSenderId: '<your-messaging-sender-id>'
  }
};

Step 5: Setup @NgModule for a AngularFireModule.

Replace the following code in the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

Now, we have successfully configured the Firebase with an Angular application.

Step 6: Make two components of the application.

Create one directory inside src  >>  app folder called components.

Go to the root of the folder and in the console and hit the following command.

ng g c index
ng g c create

We have created three components. Each component will do its job. Here we are establishing the single responsibility principle for every component.

It makes a separate folder inside src  >>  app directory. We need to move all these three folders inside components folder.

Also, we need to change the app.module.ts file, to write the correct path of the imported components. By default, it’s an app directory.

Step 7: Routing and Navigation.

The Angular Router enables navigation from one view to the next as users perform application tasks.

First, we need to import the routing modules inside our app.module.ts file.

Configuration

When we have created the components, it’s by default path is different and now we have moved to the components, so now its path is different. So, first, we need to change that path in app.module.ts file.

Okay, now we need to configure the routes. So make one file inside app directory called router.module.ts file.

Write the following code in it.

// router.module.ts

import { RouterModule } from '@angular/router';
import { CreateComponent } from './components/create/create.component';
import { IndexComponent } from './components/index/index.component';

export const appRoutes: Routes = [
  { path: 'create',
    component: CreateComponent
  },
  { path: 'index',
    component: IndexComponent
  }
];

We have defined one array, and inside that array, we have registered the different routes with their components. Finally, we have exported it.

Now, import this object inside app.module.ts  and register the module.

// app.module.ts

import { appRoutes } from './router.module';

imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(appRoutes)
],

Step 8: Define the Router outlet.

In the app.component.html file, write the following code.

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <nav>
    <a routerLink="create" routerLinkActive="active">Add coins</a>
  </nav>
  <router-outlet></router-outlet>
</div>

Step 9: Add Bootstrap CSS.

Download the bootstrap from its original docs and paste the CSS and JS folders inside src  >>  assets folder.
In the src >>  index.html file, add the bootstrap css file.

<link rel="stylesheet" href="assets/css/bootstrap.min.css">

Also, change the app.component.html outlook due to bootstrap classes.

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <ul class="nav navbar-nav">
      <li>
        <a routerLink="create">
          Add Share
        </a>
      </li>
      <li>
        <a routerLink="index">
          Display Shares
        </a>
      </li>
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Step 10: Make a form in the create a component file.

First, our create.component.ts file looks like this.

// create.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  title = 'Share Market';
  constructor() { }

  ngOnInit() {
  }

}

And then, we need to make the create.component.html form design.

<div class="panel panel-primary">
  <div class="panel-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Share Name</label>
        <input type="text" class="form-control" name="name"/>
      </div>
      <div class="form-group">
        <label class="col-md-4">Share Price</label>
        <input type="text" class="form-control" name="coin_price"/>
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-primary">Add</button>
        </div>
    </form>
  </div>
</div>

Now, head over to this. http://localhost:4200/create . It looks like this.

 

Angular 5 Firebase Tutorial

Step 11: Create services to send http requests.

Type the following command in your terminal.

ng g service share

Now, import the service file into the app.module.ts file.

import { ShareService } from './coin.service';

providers: [ShareService]

Now, first, we will insert the values in the Firebase database.Include the ReactiveFormsModule in the app.module.ts file.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(appRoutes),
    ReactiveFormsModule
  ],

Then, we are validating the forms. So first write the form HTML in the create.component.html. 

<div class="panel panel-primary">
  <div class="panel-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Share Name</label>
        <input type="text" class="form-control" formControlName="name" #name />
      </div>
      <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Share Price</label>
        <input type="text" class="form-control" formControlName="price" #price/>
      </div>
      <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['price'].errors.required">
          Price is required.
        </div>
      </div>
        <div class="form-group">
          <button (click)="addShare(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
        </div>
    </form>
  </div>
</div>

Also, we need to write the logic of validation in the create.component.ts file.

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { ShareService } from '../../share.service';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  angForm: FormGroup;
  constructor(private shareservice: ShareService, private fb: FormBuilder) {
    this.createForm();
   }
  createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required ],
      price: ['', Validators.required ]
   });
  }
  addShare(name, price) {
     const dataObj = {
      name: name,
      price: price
    };
    this.shareservice.addShare(dataObj);
  }
  ngOnInit() {
  }
}

Write the share.service.ts file to insert the data into the database.

// share.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class ShareService {

  private basePath = '/shares';
  public items: any;
  public item: any;
  constructor(private db: AngularFireDatabase) { }

  addShare(data) {
  const obj = this.db.database.ref(this.basePath);
  obj.push(data);
  console.log('Success');
  }
}

If all of your database configurations are right then now you can insert the values in the Firebase. You can see on your console. If you do not know how to configure the Firebase then check out my React Firebase Tutorial

Step 12: Display the shares data in our application.

Now, go to the index.component.ts file and replace the whole file with the following code.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ShareService } from '../../share.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  public shares: Observable<any[]>;
  constructor(private shareservice: ShareService) { }

  ngOnInit() {
    this.shares = this.getShares('/shares');
  }
  getShares(path) {
    return this.shareservice.getShares(path);
  }
}

Our final share.service.ts file looks like this. I have coded the fetching the data from the firebase function.

// share.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ShareService {

  private basePath = '/shares';
  constructor(private db: AngularFireDatabase) { }

  addShare(data) {
  const obj = this.db.database.ref(this.basePath);
  obj.push(data);
  console.log('Success');
  }

  getShares(path): Observable<any[]> {
    return this.db.list(path).valueChanges();
  }
}

And finally, our view file index.component.html looks like this.

<table class="table table-striped">
  <tr>
    <th>Share Name</th>
    <th>Share Price</th>
  </tr>
  <tr *ngFor="let share of shares | async">
    <td>{{ share.name }}</td>
    <td>{{ share.price }}</td>
  </tr>
</table>

 

Firebase Angular Tutorial Example From Scratch

Fork Me On Github

That is it, Guys. Angular Firebase Tutorial With Example From Scratch is over. Thanks.

.

 

 

 

The post Angular Firebase Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/feed/ 14
React.js Firebase Tutorial https://appdividend.com/2017/07/22/react-firebase-tutorial/ https://appdividend.com/2017/07/22/react-firebase-tutorial/#comments Sat, 22 Jul 2017 11:05:32 +0000 http://localhost/appdividend/?p=734 React and Firebase Tutorial

React.js Firebase Tutorial is today’s primary focus. If you do not know, what React.js then go to this tutorial Beginner’s Guide To Setup React Environment on this website and you will know about React.js. It is the popular front end library used by many big companies and created by Facebook. Today we will create a chat […]

The post React.js Firebase Tutorial appeared first on AppDividend.

]]>
React and Firebase Tutorial

React.js Firebase Tutorial is today’s primary focus. If you do not know, what React.js then go to this tutorial Beginner’s Guide To Setup React Environment on this website and you will know about React.js. It is the popular front end library used by many big companies and created by Facebook. Today we will create a chat application using React.js and Firebase as a backend data service. 

Firebase is the most popular backend data service provider. Firebase is a real-time database service provider. It is API that enables the integration of online chat functionality into their websites. Now, enough talking let us jump into this React.js Firebase Tutorial. You will find more info on their official website https://firebase.google.com/

If you want to learn more about React and Redux then check out this React 16.6 – The Complete Guide (incl. React Router & Redux) course.

React.js Firebase Tutorial

Step 1: Create React.js Firebase Tutorial.

Install React Starter Kit project by the following command.

npm install -g create-react-app

Now, create one app using the following command.

create-react-app react-turbo

Your starter kit’s file structure looks like this.

react firebase application

Step 2: Define our application structure.

For this project, we are using a modern CSS framework based on Flexbox called Bulma

So go to the react-turbo  >>  public  >>  index.html and paste the following CDN of Bulma CSS Framework.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.css">

We are going to create one simple message app, which is storing the message in the Firebase and will show the message in our application.

If you are working in the React.js application, you need to keep following points in your mind.

  1. You need to identify your components structure then and then you will be able to start the coding. 
  2. We need to give your application proper structure like who will become parent component and who will become child component.
  3. Communication between the components is the significant key point in the React.js. Otherwise, you will end up making a mess of your code, and all your further paths of the code will be blocked, or you will be stuck at some point, and from there you will need to rewrite whole application.

I am going to show you how I have structured my application.

Introduction to Firebase and React

 

In the upper part, our whole component called App.js

It will contain MessageList Component called MessageList.js

MessageList component contains Messages of our application getting from Firebase Database.

MessageBox component is responsible for the add messages form. It will be a textarea through which user can add the new messages.

Go to src  >>  App.js and edit the code.

// App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        React Firebase Tutorial
      </div>
    );
  }
}

export default App;

Start the development server by typing following command.

npm start

The development server is started, and you can see in the browser by going following  URL. It will automatically open the browser window.

http://localhost:3000/

We can see that in browser “React Firebase Tutorial.

Step 3: Define app.js file.

Now, we need to create two components. So first create one folder inside src folder and name it as “components.

App.js will be by default provided by React Application.

App.js file is included in index.js file.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

So, the main component of our app is App.js

The first component would be “MessageList.js.”

The second component would be “Message.js.”

Step 4: Create MessageList component.

Create the first component called MessageList.js

// MessageList.js

import React, {Component} from 'react';

class MessageList extends Component {
  render(){
    return (
      <div>
        MessageList Component
      </div>
    )
  }
}

export default MessageList

This component contains all the messages to display. So first we need to define an array of messages in the constructor.

// MessageList.js

constructor(props){
    super(props);
    this.state  = {
      messages: []
    }
  }

If we are going to use the constructor in our app, then we call the props from the parent component. Otherwise, it will not work.

Here I have to define default state of messages array, and it is empty. But in future, we need to fill this with the messages given by Firebase Application.

Now, include this component into the App.js, our main component.

// MessageList.js

import React, { Component } from 'react';
import MessageList from './components/MessageList';

class App extends Component {
  render() {
    return (
      <div>
        <MessageList />
      </div>
    );
  }
}

export default App;

You will see in the browser that “MessageList Component” will display.

Step 5: Create header component.

We also create one another component called Header.js

// Header.js

import React, {Component} from 'react';

class Header extends Component {

  render(){
    return (
      <nav className="navbar">
        <div className="navbar-brand">
          <a className="navbar-item" href="http://bulma.io">
            {this.props.title}
          </a>
        </div>
      </nav>
    )
  }
}
export default Header

Here I have provided one property called title, you can see like {this.props.title}

Remember that I have used Bulma as CSS Framework so, the class names are may not be familiar to you.

In React.js class is reserved keyword so instead of using class in CSS property use className

Include this Header in the App.js file.

// App.js

render(){
     return (
      <div className="container">
          <Header title="Simple Firebase App" />
          <MessageList />
      </div>
    );
}

Step 6: Create Message component.

Create one component called Message.js and put the following code in it.

// Message.js

import React, {Component} from 'react';

class Message extends Component {

  render(){
    return (
      <div>
        {this.props.message}
      </div>
    )
  }
}
export default Message

Here we get all the messages one by one as a property of MessageList component.

Step 7: Configure Firebase Database.

Now we need to create and configure Firebase Database

Firebase is a product of Google, so you need to have at least one Google account.

Now, go to this URL: https://firebase.google.com/

If you are signed in to Google, then you will see the following screen.

React and Firebase Application

Now, click the Go To Console button. You will see the following screen.

Firebase Database Service

Now, click the Add Project title. 

Create Firebase Project

Name your project and select your country and click the Create Project button. You will see this screen.

Firebase Authentication

 

Now, here we need to configure our project for the web. So click “Add Firebase to your web app” button.

You will find two scripts file with your project related configurations. You need to copy 2nd script with the config object.

We include Firebase via NPM so, go to the terminal and type following command

npm i firebase --save

Include this package in App.js file.

// App.js

import firebase from 'firebase';

In the App.js file’s constructor, we are going to configure the Firebase. So Copy the following code and put it in your constructor.

// App.js

var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "appdividend-c8a0f",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

I have emptied out all the values, but you have those value just copy paste it from the Firebase Console or copy from your console and paste it here. Now, we have successfully connected with our Firebase database service.

Step 8: Include the config object of Firebase.

But we need to use this service in the MessageList component. Remember this component is responsible for the getting all the messages from the database. So we need to pass this Firebase reference to this component via properties.

So our App.js file is looking like this.

// App.js

import React, { Component } from 'react';
import MessageList from './components/MessageList';
import Header from './components/Header';
import firebase from 'firebase';

class App extends Component {

constructor(props){
  super(props);
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);
}

  render() {
    return (
      <div className="container">
            <Header title="Simple Firebase App" />
            <div className="columns">
              <div className="column is-3"></div>
              <div className="column is-6">
                <MessageList db={firebase} />
              </div>
            </div>
        </div>
    );
  }
}

export default App;

Step 9: Create component called MessageBox.js

Create one another component inside components folder called “MessageBox.js.

// MessageBox.js

import React, {Component} from 'react';

class MessageBox extends Component {
  render() {
        return (
          <form>
            <textarea
                className="textarea"
                placeholder="Type a message"
                cols="100">
              </textarea>
          </form>
        )
  }
}

export default MessageBox

Include this file in App.js.  So our file will look like this.

// App.js

import React, { Component } from 'react';
import MessageList from './components/MessageList';
import ChannelList from './components/ChannelList';
import MessageBox from './components/MessageBox';
import Header from './components/Header';
import firebase from 'firebase';

class App extends Component {

  constructor(props){
    super(props);
    firebase.initializeApp({
      apiKey: "",
      authDomain: "",
      databaseURL: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: ""
    });
  }

  render(){
    return (
      <div className="container">
            <Header title="Simple Firebase App" />
            <div className="columns">
              <div className="column is-3"></div>
              <div className="column is-6">
                <MessageList db={firebase} />
              </div>
            </div>
            <div className="columns">
              <div className="column is-3"></div>
              <div className="column is-6">
                <MessageBox db={firebase} />
              </div>
            </div>
        </div>
    )
  }
}

export default App;

Step 10: Setup database rules.

Now, we need to add the message to our database and make sure that in your firebase app you will have both permissions and read as well as write.

So go to your console and click in the Database section on the left side. Now go to the rules tab. You need to give both permissions to true like the following image.

Firebase Database Permission

 

I am ignoring all the Securities issues right now because It’s a demo app, but in real-time, you need to provide proper authentication for that.

Switch to your editor and open the MessageBox.js component. Put the following code in it. I will explain you this.

// MessageBox.js

import React, {Component} from 'react';
import trim from 'trim';

class MessageBox extends Component {

  constructor(props){
    super(props);
    this.onChange = this.onChange.bind(this);
    this.onKeyup = this.onKeyup.bind(this);
    this.state = {
      message: ''
    };
  }
  onChange(e){
      this.setState({
        message: e.target.value
      });
  }
  onKeyup(e){
    if(e.keyCode === 13 && trim(e.target.value) !== ''){
      e.preventDefault();
      let dbCon = this.props.db.database().ref('/messages');
      dbCon.push({
        message: trim(e.target.value)
      });
      this.setState({
        message: ''
      });
    }
  }
  render() {
    return (
      <form>
        <textarea
            className="textarea"
            placeholder="Type a message"
            cols="100"
            onChange={this.onChange}
            onKeyUp={this.onKeyup}
            value={this.state.message}>
          </textarea>
      </form>
    )
  }
}

export default MessageBox

Here, First of all, I have downloaded one more package called ‘trim‘ via NPM and imported as well.

Now, I have used Two events of any Textbox or Textarea, which is

  1. onChange()
  2. onKeyUp()

onChange() event set the current state of textarea value, and onKeyUp() will fire when someone presses the enter key to send the message. Trim package is used for trailing the whitespace from the typed message.

We are using the Firebase database instance from the properties provided by App.js

Now, pushing(saving) the typed value to the Firebase in onKeyUp() function.

Okay, finally switch the http://localhost:3000 You will see something like this.

React Firebase Chat App

 

Now, fill the new message and press enter.

If the Firebase is configured correctly then, you will be able to see the following screen.

Firebase React Tutorial

 

Firebase will automatically generate the new key for us and save our message into the database.

Step 11: Display the messages in our application.

Now, all we need is to display the message in our application. So put the following code in our MessageList.js file

// MessageList.js

import React, {Component} from 'react';
import Message from './Message';
import _ from 'lodash';

class MessageList extends Component {
  constructor(props){
    super(props);
    this.state = {
      messages: []
    };
    let app = this.props.db.database().ref('messages');
    app.on('value', snapshot => {
      this.getData(snapshot.val());
    });
  }

  getData(values){
    let messagesVal = values;
    let messages = _(messagesVal)
                      .keys()
                      .map(messageKey => {
                          let cloned = _.clone(messagesVal[messageKey]);
                          cloned.key = messageKey;
                          return cloned;
                      })
                      .value();
      this.setState({
        messages: messages
      });
  }

  render() {
    let messageNodes = this.state.messages.map((message) => {
      return (
        <div className="card">
          <div className="card-content">
            <Message message = {message.message} />
          </div>
        </div>
      )
    });
    return (
      <div>
        {messageNodes}
      </div>
    );
  }
}

export default MessageList

I am explaining you, what is happening here.

First, I would like to download a new package from NPM called ‘lodash.’

If you want to program functionally and you need to deal with lots of arrays as well as objects then in javascript you should definitely use this library. It is quite a famous library in Functional JavaScript Programming.

In the constructor, I am using the database reference to call the Firebase server reference to get the messages data. It will return a Promise, and when It resolves, we get our data. Here the URL or Reference for the Firebase is ‘/messages.’ Messages are one of the nodes of firebase, and we are getting all of its children as data. 

The data is returned as an Object, and we are storing this values in an array that is why we are using the lodash module to convert an Object into an Array.

Finally, iterate an array and put the value in Message component as a property and Message component displays the messages.

Now, go to the http://localhost:3000/

You will see one message is displaying and in below message box is also there.

React Firebase Simple Tutorial

Enter a 4-5 messages more, and without refresh, the messages will be displayed.

Simple React Tutorial

 

You can learn more about Firebase like how to update and delete a record. I have not covered in this tutorial but will cover in next React tutorial. For more, refer:  https://firebase.google.com/docs/reference/js/firebase.database

Now, Finally, Our today’s topic React.js Firebase Tutorial is over.

I am putting this code in Github Repo.

Githubhttps://github.com/KrunalLathiya/React-and-Firebase-Tutorial

Steps To Use Github Code:

  1. Clone the repo.
  2. Go to the project and run “npm install”
  3. Go to the https://firebase.google.com/ Firebase console and configure the database.
  4. Open a browser and go to http://localhost:3000

 

Still Doubt? Ask in a comment below. I am happy to help you.

The post React.js Firebase Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2017/07/22/react-firebase-tutorial/feed/ 16