Firebase as simple database to React app

Firebase as simple database to React app

In this tutorial you're going to learn how to use Firebase Real Time Database service in React application


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.

Here is the final application:

Create your database application

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

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

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.


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


Creating config.js file

Let’s write Firebase configuration in a separate config.js file:

const config = {
firebase:{
apiKey: "AIzaSyAgBvGKlPEySB6vCWVkyO5OnRiVP3pzgps",
authDomain: "react-firebase-basic.firebaseapp.com",
databaseURL: "https://react-firebase-basic.firebaseio.com",
}
}

export default config;

You’ll import this config into your App.js later.


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);

<span class="hljs-keyword">this</span>.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 componentDidMount and componentDidUpdate 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.

// ...
render() {
const { developers } = this.state;
return(
<div className="container">
<div className="row">
<div className='col-xl-12'>
<h1>Firebase Development Team</h1>
</div>
</div>
<div className='row'>
<div className='col-xl-12'>
{
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>
<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>
</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>
)
}

handleSubmit = (event) => {
event.preventDefault();
let name = this.refs.name.value;
let role = this.refs.role.value;
let uid = this.refs.uid.value;

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;
this.setState({ developers });
}
else if (name && role ) {
const uid = new Date().getTime().toString();
const { developers } = this.state;
developers.push({ uid, name, role })
this.setState({ developers });
}

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;
});
this.setState({ developers: newState });
}

updateData = (developer) => {
this.refs.uid.value = developer.uid;
this.refs.name.value = developer.name;
this.refs.role.value = developer.role;
}

Now your React application is ready to read and set data into your Firebase database. Here is the final demo again:



Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.

How to Email authentication with React Native and Firebase

How to Email authentication with React Native and Firebase

In each and every app, you will see several kinds of authentication like login with Facebook, Google etc. But still, people prefer to entering email and password. In this tutorial, we are going to integrate Email authentication with React native and Firebase. Using firebase makes it easier to use.

Tip: Use Bit (GitHub) to easily share your React components into a reusable collection your team can use and develop across projects. Build modular apps faster as a team, save time and make life a bit easier. Give it a try.

Semantic UI components with Bit: Easily turn your components into a reusable collection

Email Authentication with React native, Firebase and Expo:

We’ll be using Expo without getting into Xcode or Android studio. Open up your terminal or command line and type in:

expo init fb-react-native-firebase

After hitting enter, you will see the screen as shown below, where you can enter the name of the app and slug. After that hit enter again.

Once the installation is complete, you will see the following screen:

We will be developing this project using VS Code. In VSC, open a new terminal, cd to your app’s folder and run <strong>yarn start</strong> .

The Expo will open a new window in the browser, as shown below. There you can see options for running the app using an android emulator or device. iOS simulator and by using a QR Code scanner. We are using an Android emulator to showcase this app.

After that, open up your emulator and use it to open the expo app.

Emulators use too much of your system’s memory. I tried using Android on Mac and it’s eating so much space.

So now we are ready to code.

Bootstrap form quickly with a native base

To design our interface faster and smoother we are using Native base for developing this app. You can check out the native base for more information. So let’s move on to the next step

Open a new terminal and run <strong>npm i native-base</strong>

Next step to import necessary Native base component to <strong>App.js</strong>

import { Container, Item, Form, Input, Button, Label } from "native-base";

And construct form interface

render() {
    return (
      <Container>
        <Form>
          <Item floatingLabel>
            <Label>Email</Label>
            <Input autoCapitalize="none" autoCorrect={false} />
          </Item>
          <Item floatingLabel>
            <Label>Password</Label>
            <Input
              secureTextEntry={true}
              autoCapitalize="none"
              autoCorrect={false}
            />
          </Item>
          <Button full rounded success>
            <Text>Login</Text>
          </Button>
        </Form>
      </Container>
    );
  }

When you save the result, you can see them instantly on the screen. This is a feature called as Hot-reloading.

A form appears on the top.

Now, form design is ready. Let’s move on to the main programming part.

Add firebase to React native project

Let’s add firebase with npm i firebaseand import firebase on App.js and then import that into our project.

import * as firebase from "firebase";

In the next step, you need to **create a firebase project. Goto firebase console **and make one as shown below:

Now grab configuration apikey which very important to access the data from the database.

And paste to App.js as shown below in the code structure.

import * as firebase from "firebase";
import { Container, Item, Form, Input, Button, Label } from "native-base";
var config = {
    apiKey: "AIzaSyDFdsjQWG8IFLXmviNqSiVZMw_ADFl5tpo",
    authDomain: "react-native-firebase-3bde9.firebaseapp.com",
    databaseURL: "https://react-native-firebase-3bde9.firebaseio.com",
    projectId: "react-native-firebase-3bde9",
    storageBucket: "react-native-firebase-3bde9.appspot.com",
     messagingSenderId: "269398778466"
};
firebase.initializeApp(config);

Now, we have successfully added firebase to our project.

Sign Up

For email authentication, we need to activate Email authentication on Firebase console.

Let’s jump back to VS Code and add a signup button to it.

<Button full rounded success style={{ marginTop: 20 }}> <Text>Signup</Text>
</Button>

Result view should be

Now we have to add signup code.

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
  }
  SignUp = (email, password) => {
    try {
      firebase
          .auth()
          .createUserWithEmailAndPassword(email, password)
          .then(user => { 
                 console.log(user);
           });
} catch (error) {
      console.log(error.toString(error));
    }
  };

We create a state for handle email and password from. We have created the form and SignUp function for handling firebase code.

Next, add form value to state with on ChangeText.

<Item floatingLabel>
            <Label>Email</Label>
            <Input
              autoCapitalize="none"
              autoCorrect={false}
              onChangeText={email => this.setState({ email })}
            />
          </Item>
          <Item floatingLabel>
            <Label>Password</Label>
            <Input
              secureTextEntry={true}
              autoCapitalize="none"
              autoCorrect={false}
              onChangeText={password => this.setState({ password })}
            />

And we trigger SignUp function with onPress event from Signup button.

onPress={() => this.SignUp(this.state.email, this.state.password)}

Save and try to submit a form.

After submitting the data goto firebase console and check that the data you have entered is coming there or not.

Now we have added data successfully in Firebase as a new user.

Login

For login, we use code from sign up method and change firebase function.

Login = (email, password) => {
    try {
      firebase
         .auth()
         .signInWithEmailAndPassword(email, password)
         .then(res => {
             console.log(res.user.email);
      });
} catch (error) {
      console.log(error.toString(error));
    }
  };

After you need to use the **onAuthStateChanged method **to get user data. Then add an onPress method to SignIn Buton.

onPress={() => this.LogIn(this.state.email, this.state.password)}

Let’s try signing in.

Finally we have made it. We got the data from the firebase user database.

Conclusion

In this tutorial, you have learned about how to setup react native project with expo and firebase. You have also learned, how to kickstart construct UI with NativeBase? Then after that, we have created a basic email authentication using React Native, Firebase and expo.

We hope you got something from this. Thanks for reading!

Intermediate React and Firebase Tutorial - Build an Evernote Clone

Intermediate React and Firebase Tutorial - Build an Evernote Clone

Intermediate React and Firebase Tutorial - Build an Evernote Clone: In this intermediate React.js tutorial, we create a clone of the popular note-taking application Evernote. This app will allow us to create notes with a full text editor, and update live to a database using Firebase.

In this intermediate React.js tutorial, we create a clone of the popular note-taking application Evernote. This app will allow us to create notes with a full text editor, and update live to a database using Firebase.

Thanks for watching

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about React, Redux and Django

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

Best 50 React Interview Questions for Frontend Developers in 2019

Learn React - Full Course for Beginners - React Tutorial 2019

React (without Redux) - JWT Authentication Tutorial & Example

React vs Angular vs Vue.js by Example

MERN Stack Tutorial - Build a MERN App From Scratch ❤

State Management with React Hooks

💻 Code: https://github.com/Zackazt/evernote-clone