Saturday, January 25, 2020

React and Firebase Realtime Database Read data.

In last post we have seen how to write data in  React and Firebase. In this we are going to go through how to read value and json from firebase realtime Database.

Read simple data from Realtime Database

Now we will open the App.js file of the react app.
First, we have to import firebase as
import * as firebase from 'firebase'
We need to do all the work inside the componentDidMount() function.
firebase.database().ref().child('name').on('value',snap =>{
    this.setState({
      name:snap.val()
    });
});
In the above example, we try to get the value of name from a tree using .on function. There is a parameter snapshot in .on function. And we will get all results in the snapshot parameter. We are trying to set the value to the state so we can use in our web.

Read Json data from Realtime Database

firebase.database().ref().child('userData').on("value", snapshot=> {
  var newPost = snapshot.val();
  this.setState({
    userData:newPost
  });
});
In the above example, we try to get the value of userData from a tree using .on function.

Read Array Json data from Realtime Database

firebase.database().ref().child('users').on("value", snapshot=> {
  let all = snapshot.val();
  let data =[];
  for (let i in all){
    data.push({
        id:i, 
        Name:all[i].Name,
        email:all[i].email,
        profile_picture:all[i].profile_picture
    });

  }

  console.log(data);

  this.setState({
      users:data
  });

});
In the above example, we try to get the value of users from a tree using .on function.

Here is the full code of the above examples.

import './App.css';

import * as firebase from 'firebase'

import React, { Component } from 'react'

export default class App extends Component {

  constructor(){
    super();
    this.state={
      name:"",
      users:[],
      userData:{}
  };
  }

componentDidMount(){
  firebase.database().ref().child('name').on('value',snap =>{
    this.setState({
      name:snap.val()
    });
});

firebase.database().ref().child('userData').on("value", snapshot=> {
  var newPost = snapshot.val();
  this.setState({
    userData:newPost
  });
});

firebase.database().ref().child('users').on("value", snapshot=> {
  let all = snapshot.val();
  let data =[];
  for (let i in all){
    data.push({
        id:i, 
        Name:all[i].Name,
        email:all[i].email,
        profile_picture:all[i].profile_picture
    });

  }

  console.log(data);

  this.setState({
      users:data
  });

});

}

  render() {
    return (
      <div className="App">
        <h1>{this.state.name}</h1>
        <div> <h1>User Infromation </h1></div>
        <h3>Name:{this.state.userData.Name}</h3>
        <h3>Email:{this.state.userData.email}</h3>
        <h3>Image:{this.state.userData.profile_picture}</h3>
        <div> <h1>All Users</h1>
        {this.state.users.map((value)=>{
                 return(
                     <div key={value.id}>
                        <h3>Name:{value.Name}</h3>
                        <h3>Email:{value.email}</h3>
                        <h3>Image:{value.profile_picture}</h3>
                     </div>
                 )
               })}
        </div>
      </div>

    )
  }
}

Hope this post will help with you projects. Message if you stuck anywhere.

Enjoy coding...

React and Firebase Realtime Database Write data.

In last post we have seen how to setup react and firebase. In this we are going to go through how to write value and json to  firebase realtime Database.

Before jumping to code in react we have to set permission write:true and read:true in the firebase console. After update don't forgot to click publish button.

enter image description here
After change the permission select the Realtime Database.
enter image description here
You will see the tree structure of data in Data tabs. You can import Json file and add manually one by one data. Now we will jump to the react code. 

Write simple data to Realtime Database


Now we will open the App.js file of the react app.

First, we have to import firebase as
import * as firebase from 'firebase'
We need to do all work inside the componentDidMount() function.
  firebase.database().ref().set({
    name:"Sushil"
  }, function(error) {
    if (error) {
        console.log(error);
      // The write failed...
    } else {
    console.log("Data Updated");
      // Data saved successfully!
    }
  });
In the above code firebase as we imported. database().ref() gives access to the reference of the realtime database. .set is a function for adding data to the database. If you use .setfunction it will delete the below data and create new on the reference tree.
If we don't wont to lose existing data then we have to use .update function instead of .set function. Below is the same example with adding new item.
 firebase.database().ref().update({
    lastName:"Kumar"
  }, function(error) {
    if (error) {
        console.log(error);
      // The write failed...
    } else {
    console.log("Data Updated");
      // Data saved successfully!
    }
  });
If there is a key in the tree with same name then it will update the item value and it will not harm to the other trees.

Write simple Json data to Realtime Database

The way we write the simple data value in the same way we are going to add Json Data. Here also we have .set function and .update function and both work the same way. .set function clean everything of reference database tree and write a new one but .update function write without cleaning.
firebase.database().ref().update({
    userData: {"Name":"Sushil Kumar",
    email: "sushil@gmail.com",
    profile_picture : "imageUrl"}
}, function(error) {
    if (error) {
        console.log(error);
      // The write failed...
    } else {
    console.log("Data Updated");
      // Data saved successfully!
    }
});

Write Array Json data to Realtime Database

Here also we can use `.set` and `.update` same way as we mention in above examples.

firebase.database().ref().update({
  users: [{"Name":"Sushil Kumar",
  email: "sushil@gmail.com",
  profile_picture : "SushilUrl"},{"Name":"Mahesh Kumar",
  email: "mahesh@gmail.com",
  profile_picture : "maheshUrl"}]
}, function(error) {
  if (error) {
      console.log(error);
    // The write failed...
  } else {
  console.log("Data Updated");
    // Data saved successfully!
  }
});

Here is the full code of the above examples.
import './App.css';

import * as firebase from 'firebase'

import React, { Component } from 'react'

export default class App extends Component {

  constructor(){
    super();
  }

componentDidMount(){
  firebase.database().ref().set({
    name:"Sushil"
  }, function(error) {
    if (error) {
        console.log(error);
      // The write failed...
    } else {
    console.log("Data Updated");
      // Data saved successfully!
    }
  });

  firebase.database().ref().update({
    lastName:"Kumar"
  }, function(error) {
    if (error) {
        console.log(error);
      // The write failed...
    } else {
    console.log("Data Updated");
      // Data saved successfully!
    }
  });

firebase.database().ref().update({
    userData: {"Name":"Sushil Kumar",
    email: "sushil@gmail.com",
    profile_picture : "imageUrl"}
}, function(error) {
    if (error) {
        console.log(error);
      // The write failed...
    } else {
    console.log("Data Updated");
      // Data saved successfully!
    }
});

firebase.database().ref().update({
  users: [{"Name":"Sushil Kumar",
  email: "sushil@gmail.com",
  profile_picture : "SushilUrl"},{"Name":"Mahesh Kumar",
  email: "mahesh@gmail.com",
  profile_picture : "maheshUrl"}]
}, function(error) {
  if (error) {
      console.log(error);
    // The write failed...
  } else {
  console.log("Data Updated");
    // Data saved successfully!
  }
});


}

  render() {
    return (
      <div className="App">
        <h1>React and Firebase</h1>
      </div>
    )
  }
}


Hope this post will help with you projects. Message if you stuck anywhere.

Enjoy coding...





React And Firebase Reatime Database Installation and Setup.

Starting react with firebase realtime database is too easy. You just need some patience and practice to be perfect in it. Today I just completed this whole react and firebase. I thought I should publish it because it will be going to help me further. It is very common in people to forget things we learned just a day before. If i will forget then this post will be helping to memorized all movements of today learning. Here I will start first to initialize both firebase and react.

First Create React App

npm create-react-app your-app-name
cd my-app

Now Install firebase using NPM 

npm install firebase --save 
npm start

After done start your server and open index.js file from your project. 


import * as firebase from 'firebase';
var config = {
    apiKey: "XXXXXXXXXXXXXXXXXXXXXX",
    authDomain: "XXXXXXXXX-XXXXXXXX.firebaseapp.com",
    databaseURL: "https://XXXXXXXXXXX-XXXXXXX.firebaseio.com",
    projectId: "XXXXXXXXXX-XXXXXXXXXXX",
    storageBucket: "XXXXXXXXXXXXXX-XXXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXXXXX",
    appId: "1:XXXXXXXXXXXXX:web:c2fd2ac48cd69a49471438",
    measurementId: "XXXXXXXXXXX"
  };
firebase.initializeApp(config);

  1. Do above things as mention first you have to import  from firebase.
  2. Update the config file from your project. Below there is a way to access the config file go through the steps.
  3. And finally initialize firebase with config file.

Get config object for your web app

To get the config object for a Firebase Web App:
  1. Sign in to Firebase, then open your project.
  2. Click the Settings icon, then select Project settings.
  3. In the Your apps card, select the nickname of the app for which you need a config object.
  4. Select Config from the Firebase SDK snippet pane.
  5. Copy the config object snippet, then add it to your app's HTML.

Hope this setup help with you project message if you stuck anywhere.

Enjoy coding...