create account

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

View this thread on: hive.blogpeakd.comecency.com
· @pckurdu ·
$25.30
Build An Application With React Hooks, Material-UI and Firebase (Part3)
![react-hook.fw.png](https://cdn.steemitimages.com/DQmRb5hzDr5oAwMJnF7kLE1Q18G6Bn2DhY7AX8ZWxzkmEpB/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](https://cdn.steemitimages.com/DQmPHw6srzHGSoHLh1wbYoRWVU2j39ufTQwGPNaWgEeAcCf/react1.gif)
<br>
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](https://cdn.steemitimages.com/DQmcW4TEt3pZsbRgMCHENpMK4mMJ28RQQwsd6sGMr5rEa3e/react2.gif)
<br>
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()
```
<br>
### 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)
    }
```
<br>
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()
    }
```
<br>
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
        })
    }
```
<br>
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
        })
    }
```
<br>
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'
```
<br>
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)
        }
    }
```
<br>
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>
```
<br>
![react3.gif](https://cdn.steemitimages.com/DQmeiJ5sjurK6GXXbz79Xzh5H8jMoq5c8gVETpxNbrb6NfM/react3.gif)
<br>
#### 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)
        }
    }
```
<br>
![react4.gif](https://cdn.steemitimages.com/DQmSJmcNpANUWwtEQPk5cMLVDKNauX2QhVnL6mrM6CyRxEk/react4.gif)
<br>
# 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
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 56 others
properties (23)
authorpckurdu
permlinkbuild-an-application-with-react-hooks-material-ui-and-firebase-part3
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","react","material-ui","firebase"],"image":["https://cdn.steemitimages.com/DQmRb5hzDr5oAwMJnF7kLE1Q18G6Bn2DhY7AX8ZWxzkmEpB/react-hook.fw.png","https://cdn.steemitimages.com/DQmPHw6srzHGSoHLh1wbYoRWVU2j39ufTQwGPNaWgEeAcCf/react1.gif","https://cdn.steemitimages.com/DQmcW4TEt3pZsbRgMCHENpMK4mMJ28RQQwsd6sGMr5rEa3e/react2.gif","https://cdn.steemitimages.com/DQmeiJ5sjurK6GXXbz79Xzh5H8jMoq5c8gVETpxNbrb6NfM/react3.gif","https://cdn.steemitimages.com/DQmSJmcNpANUWwtEQPk5cMLVDKNauX2QhVnL6mrM6CyRxEk/react4.gif"],"links":["https://github.com/facebook/react","https://github.com/mui-org/material-ui","https://github.com/pckurdu","https://github.com/pckurdu/Build-An-Application-With-React-Hooks-Material-UI-and-Firebase-Part3","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"],"app":"steemit/0.1","format":"markdown"}
created2019-03-01 20:50:15
last_update2019-03-01 20:50:15
depth0
children5
last_payout2019-03-08 20:50:15
cashout_time1969-12-31 23:59:59
total_payout_value19.301 HBD
curator_payout_value6.002 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,514
author_reputation23,385,816,696,918
root_title"Build An Application With React Hooks, Material-UI and Firebase (Part3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,599,130
net_rshares40,448,393,372,621
author_curate_reward""
vote details (120)
@portugalcoin ·
$10.93
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](https://join.utopian.io/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](https://review.utopian.io/result/8/2-1-1-1-3-3-2-3-).

---- 
Need help? Chat with us on [Discord](https://discord.gg/uTyJkNm).

[[utopian-moderator]](https://join.utopian.io/)
👍  , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorportugalcoin
permlinkre-pckurdu-build-an-application-with-react-hooks-material-ui-and-firebase-part3-20190301t230542364z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["pckurdu"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/2-1-1-1-3-3-2-3-","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2019-03-01 23:05:42
last_update2019-03-01 23:05:42
depth1
children1
last_payout2019-03-08 23:05:42
cashout_time1969-12-31 23:59:59
total_payout_value8.314 HBD
curator_payout_value2.616 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length716
author_reputation599,460,589,822,571
root_title"Build An Application With React Hooks, Material-UI and Firebase (Part3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,602,960
net_rshares17,388,128,036,550
author_curate_reward""
vote details (21)
@utopian-io ·
Thank you for your review, @portugalcoin! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-pckurdu-build-an-application-with-react-hooks-material-ui-and-firebase-part3-20190301t230542364z-20190304t071302z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-03-04 07:13:03
last_update2019-03-04 07:13:03
depth2
children0
last_payout2019-03-11 07:13:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length64
author_reputation152,955,367,999,756
root_title"Build An Application With React Hooks, Material-UI and Firebase (Part3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,712,070
net_rshares0
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-build-an-application-with-react-hooks-material-ui-and-firebase-part3-20190301t235944z
categoryutopian-io
json_metadata"{"app": "beem/0.20.18"}"
created2019-03-01 23:59:45
last_update2019-03-01 23:59:45
depth1
children0
last_payout2019-03-08 23:59:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length286
author_reputation23,214,230,978,060
root_title"Build An Application With React Hooks, Material-UI and Firebase (Part3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,604,281
net_rshares0
@utopian-io ·
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](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

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

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-build-an-application-with-react-hooks-material-ui-and-firebase-part3-20190302t101138z
categoryutopian-io
json_metadata"{"app": "beem/0.20.17"}"
created2019-03-02 10:11:39
last_update2019-03-02 10:11:39
depth1
children0
last_payout2019-03-09 10:11:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length589
author_reputation152,955,367,999,756
root_title"Build An Application With React Hooks, Material-UI and Firebase (Part3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,620,881
net_rshares0
@whaleit ·
Where to download these things are they for android or pc?

Posted using [Partiko Android](https://steemit.com/@partiko-android)
properties (22)
authorwhaleit
permlinkwhaleit-re-pckurdu-build-an-application-with-react-hooks-material-ui-and-firebase-part3-20190302t152459491z
categoryutopian-io
json_metadata{"app":"partiko","client":"android"}
created2019-03-02 15:25:00
last_update2019-03-02 15:25:00
depth1
children0
last_payout2019-03-09 15:25:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length128
author_reputation12,346,652,388
root_title"Build An Application With React Hooks, Material-UI and Firebase (Part3)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id80,632,810
net_rshares0