Build An Application With React Hooks, Material-UI and Firebase (Part3)

in #utopian-io5 years ago

react-hook.fw.png

Repository

React

https://github.com/facebook/react

Material-ui

https://github.com/mui-org/material-ui

My Github Address

https://github.com/pckurdu

This Project Github Address

https://github.com/pckurdu/Build-An-Application-With-React-Hooks-Material-UI-and-Firebase-Part3

What Will I Learn?

  • You will learn how to connect firebase project with react application
  • You will learn how to create a firebase project and enable authentication and firestore.
  • You will learn signInWithEmailAndPassword() and signOut() functions in firebase authentication.
  • You will learn createUserWithEmailAndPassword() function in firebase authentication.
  • You will learn currentUser property in firebase authentication.
  • You will learn updateProfile() function in firebase authentication.
  • You will learn doc() and set() functions in firebase firestore.
  • You will learn history.replace() in react-hooks.

Requirements

  • text editor (I used visual studio code editor)
  • Basic javascript information
  • Basic react information

Difficulty

  • Basic

Tutorial Contents

Hello to everyone,

We have created a react application in previous tutorials and we created the necessary infrastructure for router and material-ui. We created the design of the pages using material-ui components and learned how to use useState.

In this tutorial we will create project for application at firebase and we will enable authentication and firestore settings and create functions for register and login operations in react. We use these functions to create the login process and add data.

It is always best to create a tutorial by dividing it into sections. Below is a list of our operations:

  • Firebase Project Creation
  • Creating Firebase Connection Class
  • Using Firebase Class Functions

Let’s start

Firebase Project Creation

In order to use firebase in our applications, we must create a firebase project on the firebase web page. Since we will use authentication and firestore in our applications, we must open two this features.

You can create the firebase project as in the following gif.
react1.gif


After creating our application, we have to activate the features we will use.

Firebase Authentication offers multiple sign-in methods. Since we will use the Email / Password logon method in our application, we must enable that method.

Since we will store the data on Cloud Firestore, we need to create a database. There are two different database creation methods Locked Mode and Test Mode. We will work in Test Mode because we do not want to define any rules.
react2.gif


We can now use firebase in our application.

Let's create firebase.js file under the components file and define the firebase setting codes here and copy the config codes for the web on Firebase. We're going to need this to connect to the firebase.

firebase.js

import app from 'firebase/app';//The app variable represents the firebase application.

//We have to import auth and firestore to use the features.
import 'firebase/auth';
import 'firebase/firebase-firestore';

//For firebase config setting, you should use your own application's information.
const config = {
    apiKey: "your_api_key",
    authDomain: "your_domain ",
    databaseURL: " your_domain ",
    projectId: " your_domain ",
    storageBucket: " your_domain.appspot.com",
    messagingSenderId: " your_senderId "
  };

class Firebase{

    constructor(){

        app.initializeApp(config)//Let config information initialize firebase
        //With this.auth and this.db variables we can access auth and firestore
        this.auth=app.auth()
        this.db=app.firestore()
    }
}

export default new Firebase()


Creating Firebase Connection Class Functions

In this section, we will create functions for the features we will use in the application.

We have created the Firebase class and we have implemented a firebase connection with the application within the constructor() function. We need a number of functions that are necessary for our need.login,register etc.

login(email,pass){
        //firebase login function
        return this.auth.signInWithEmailAndPassword(email,pass)
    }



For firebase login process, we need to use signInWithEmailAndPassword().This function takes the email and password information as a parameter and returns the result to us.

logout(){
        //firebase logout function
        return this.auth.signOut()
    }



In order to make the exit process after the login in the application, we must use signOut() function. Authentication in the signOut () function is a previously defined authentication a this.auth

  async register(name,email,pass){
        //firebase register function
        await this.auth.createUserWithEmailAndPassword(email,pass)
        //We've updated the username of the register result.
        return this.auth.currentUser.updateProfile({
            displayName:name
        })
    }



We have created the register() function to perform the register operation via the application. The register () function will register using the createUserWithEmailAndPassword() function and will update the user name according to the name parameter after registration. Therefore we defined as asynchronous.

To change the user's name, we need to know the current user. The currentUser property allows us to capture the current user. Using the updateProfile() function, we can change the displayName property so that we update the user name.

addFruit(fruit){
        //user presence control
        if(!this.auth.currentUser){
            return alert('Not authorized')
        }

        //Adding documents to the collection of pckurdu
        return this.db.doc(`pckurdu/${this.auth.currentUser.uid}`).set({
            fruit:fruit
        })
    }



While registering, we ask the user for his favorite fruit. According to the user, we will add the fruit to the firestore.

The addFruit() function will perform data insertion to the firestore if the user is logged in.

Using currentUser, we can determine whether the user is logged in or not.

To add data to the firestore, we must add the document. We can use doc() to add the document. Here we are adding the document into the pckurdu collection and the document id is determined by the user id. With the uid property in the currentUser, we can capture the id of the logged in user.

After adding the document, we can add fields to the document with set() function. We created a fruit field and printed the fruit object in the addFruit() parameter to the value of the field.

Thus, we have defined the necessary functions to register and login. We can use them now.

Using Firebase Class Functions

We should use the Firebase class functions that we created in register and login pages.

On The Register page

First of all, we have to import the firebase.js file to use the Firebase class functions.

import firebase from '../firebase'



Let's create a function to work when the register button is clicked. This function has to be asynchronous as it will trigger the register function in the firebase. When we define the register and addFruit functions according to the data in the useState, the function will work

async function onRegister(){

        try{
            //The register in the Firebase class is running with useState data.
            await firebase.register(name,email,password)
            //The addFruit in the Firebase class is running with useState data.
            await firebase.addFruit(fruit)

            //If there are no errors, they are redirected to the dashboard page.
            props.history.replace('/dashboard')
        }catch(err){
            //create an alert instantly error
            alert(err.message)
        }
    }



Forwarding to the desired page with history.replace() is performed.

Finally, we set the click moment of the register button.

<Button onClick={onRegister}>
 Register
</Button>



react3.gif

On The Login page

We will use the login function on the login page.

import firebase from '../firebase'
…
<Button onClick={onLogin}
  Sign in
</Button>
…
async function onLogin(){
        try {
            //The login in the Firebase class is running with useState data.
            await firebase.login(email,password)

            //If there are no errors, they are redirected to the dashboard page.
            props.history.replace('/dashboard')
        } catch (error) {
            alert(error.message)
        }
    }



react4.gif

Curriculum

https://steemit.com/utopian-io/@pckurdu/build-an-application-with-react-hooks-material-ui-and-firebase-part1

https://steemit.com/utopian-io/@pckurdu/build-an-application-with-react-hooks-material-ui-and-firebase-part2

Proof of Work Done

https://github.com/pckurdu/Build-An-Application-With-React-Hooks-Material-UI-and-Firebase-Part3

Sort:  

Thank you for your contribution @pckurdu.
After analyzing your tutorial we suggest the following points:

  • Excellent tutorial and very well structured and explained.

  • Thanks for following our suggestions in your previous tutorials. This tutorial is much better.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @pckurdu!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @pckurdu!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Where to download these things are they for android or pc?

Posted using Partiko Android

Coin Marketplace

STEEM 0.31
TRX 0.11
JST 0.034
BTC 64852.72
ETH 3178.07
USDT 1.00
SBD 4.20