What are the basics in React, Firebase Real-Time Database and GraphQL for Application Development?

         


       React has several changes since its release in 2013. The React16 has improved features of async rendering, return an array of elements, and better error handling. For ex, we use the react-dom to render an array called Test. First, we will define the Test component(<Test /> and it should be mounted in the root element (document.getElementbyId('root')). Then, create the function component(Test) that simply returns an array. This array can have different items. It can be written as,

   const Test = () =>{
        return [
                <li key=1>Hi </li>,
                <li key=2>How are you </li>
   ]
   }

It will render the array items in the browser. For rendering the dynamic data, create the simple array called data and have the items in it. Now, instead of rendering the flat array, just map over the data. So, first, pass the data to the component which can accessible to the Test component in props or destructure as {data}. Now, we need to replace the return with another return which will map over the data in props. This will return an item for each Test data.

 const data = [
        { Test: "Hi", id: 1 },
        { Test: "How Are you?", id: 2 }
        
      ]
      const Test = ({data}) => {
        return data.map(e => {
          return (
            <li key={e.id}>{e.Test}</li>
          )
        })
      }

      ReactDOM.render(
        <Test data={data}/>,
        document.getElementById('root')
      )

Components:  Components allows to share a state. There are 3 types of components. Those are,

1. Compound Components
2. Uncontrolled Components
3. Controlled Components

        Compound Component shares the state information between the component and children. The React Top-Level API will help you to learn more about creating react childrens or elements. It is useful to display something based on the true or false of the variable. In the Uncontrolled component, you can use DOM elements to build your form and capture the value of inputs by refs. In controlled components, the inputs accept a value as a prompt and use a callback to change a value. Here, we are not using the ref, but the data push to the form component. It is always the current value of the input without asking for a reference. It makes the state and input synchronization that makes your validation simpler which makes our data accessible via the component state. 
      There are several life cycle methods in the life span of components. The most used method of component is render. It is called when the component is first mounted. It is also called when new props come in, Set State is called and data changes. The mounting life cycle includes the following,
1. Constructor - It is called before the component is mounted and used to initialize the state.
2. GetDerivedStateFromProps is invoked after the component is constructed and fires when the component receives new props.
3. ComponentDidMount is invoked after the component is mounted. It is good to call when you load data or make network requests. Then, shouldComponentUpdate invoked if this returns false, render and componentDidUpdate won’t be called. 
4. getSnapshotBeforeUpdate called right before the recently rendered output. It is used to read the DOM to capture the value.
5. Finally, componentDidUpdate invoked after the update and update have occurred.

    All of these do changes to react in handling asynchronous information. In react applications, we create nested component trees to compose user interfaces. There will be a state in every component to get some data. But, having the state in all our app made it difficult to keep values in sync. So, instead of putting state everywhere, we put the state at the root and pass the state data component via props. This will a create parent and child component.

setState() Functionality:
        We can change the data in our application using the setState. For ex, create the booking component responsible for rendering the bookings and make this a class component. This class component has a render method and set up an initial state. So, we will add the constructor and call the props, then add super and call props. Now, Initialize "this.state" with value, and this render return just the <div> at this moment. Now, add another component responsible for rendering the h1, and this stateless functional component displays props.room. This component will be rendered in Booking. The NowStaying method takes the property of room and set the value by "this.state.room" passing that value to the tree to  NowStaying Component. Now, if you run the code in the browser, you can see "Deluxe Room". Next, we are going to add a method called addKitchen. This method set the state(this.setState({})). Usually, we pass it to an object that contains new information to overwrite whatever in the state such as "Deluxe Room with Kitchen". So, we have to trigger that function to a button next to our Now Staying Component. So, add the JSX expression that the "this.state.room" is Deluxe and we are going to render a button and an onclick that maps to this.addKitchen method. So, when you run this in the browser, you can see "Deluxe Room with Kitchen". The code should be,

<script type="text/babel">

      const NowStaying = props => <h1>{props.room}</h1>

      class Booking extends React.Component {
      constructor(props){
      super(props)
        this.state = {
          room: "Deluxe Room"
        }
        this.addKitchen = this.addKitchen.bind(this);
        }
        addKitchen = () => {
          this.setState(prevState => {
            return { room: `${prevState.room} with Kitchen`}
          })
        }
        render() {
          return (
            <div>
              <NowStaying room={this.state.room} />
              {(this.state.room === "Deluxe Room")
                ? <button onClick={this.addKitchen}>Add Kitchen</button>
                : null
              }
            </div>
          )
        }
      }

      ReactDOM.render(
        <Booking />,
        document.getElementById('root')
      )

    </script>


Fragments: In React, the components returns multiple elements. It includes the collection of list items, rows for a table etc., By using the correct rendering rules, you can add ton of additional nodes to the DOM. for ex, the app returns the header and this header can returns nav elements. The nav elements can have as many links. These JSX elements must be wrapped in enclosing tag called the Fragements. It can be represented as,

const Navelements = () => {
        <React.Fragment>
                <a href ="/"> Home </a>
                <a href ="/about">About </a>
                <a href ="/services"> Services </a>
                <a href ="/contact"> Contact </a>                    
        </React.Fragement>
}

const App = () => {
<header>
     <Nav>
            <Navelements>
    <Nav>
</header>
}

It allows you to wrap the header, nav, and navelement that return multiple elements. If we want to render items from an array, you need to know about skiing and snowboarding. Here, we will pass data to the component via props. ie, skiDictionary={skiDictionary}. Then, we will create the description list together with our component. The Description list is a HTML tag that describes a list of items. We are going to take the props and return a definition list DL that should be the mapping of props say props.skiDictionary.map. It can be written as,

<script type="text/babel">
      const schedules = [
        { id: 1, name: "Mark", division: "Admin Team" },
        { id: 2, name: "Mike", division: "Development Team" }
      ]

     const App = (props) => {
        return (
          <dl>
            {props.skiDictionary.map(term => (
              <React.Fragment key={term.id}>
                <dt>{term.name}</dt>
                <dd>{term.division}</dd>
              </React.Fragment>  
            ))}
          </dl>
        )
      }

      ReactDOM.render(
        <App skiDictionary={schedules}/>,
        document.getElementById('root')
      )
    </script>
GraphQL:  It is a data query and manipulation language for API for fulfilling queries with existing data. Based on the data model, GraphQL returns the data same format as you requested. It can be connected to any database or storage engine. GraphQL query looks like a JSON. For ex,

query{
  boards(){
    id
    name
    subscribers{
      name
      photo_thumb
    }
  }
}

The response for your query is,


Here, the shape of our request matches the shape of the response. The GraphQLfills in the values for the keys that were requested. The shape-matching is the powerful feature of GraphQL and another feature is the type system.

        In GraphQL, every field has a type associated and can be inspected in GraphiQL by clicking on it. If you click the query, you will see the available fields that you can query. The field account returns the Account and if there is an exclamation mark, that will never return null. The field asset is a function that takes an id of type int and returns an Asset but returns null if the Asset doesn't exist. All the field declarations are considered optional by default. The GraphQL schema with user-defined types User can be written as,

       type User {
            login:String!
            email: String
            #more fields
       }

      type Query {
             user(login:String!):User
             viewer: User
             #more fields
        }
      
      Here, the user has two fields: login and email, both of type String. The type Query reads the data with special importance. For ex, to query for the user of login of Balamurugan and request the field such as login, name and bio are,
      query {
           user(login: "Balamurugan" ) {
                    login
                    name
                    bio
            }
    }
It returns as,

    {
       "data": {
            :user": {
                "login" : "Balamurugan",
                "name" : "Balamurugan",
                 "bio" : "This is the test bio"
              }
        }

    }
It is good to use the named query where the name goes right after the query keyword. Variables can be defined in query arguements such as "query getUser($login:String!)".  This variable will be passed as a arguement of a user field. GraphQL enforces the correctness of inputs and returns an error if it doesn't satisfy the specification. It allows multiple queries to one and the fields in the result must match the fields in the query. So, craft the queries to return all data your application might need in one single request.

Read and Write Data from Firebase: Firebase database allows user-specific data to the Firebase. It is synced across all clients in real-time and remains available offline. When the user goes online, the changes are synched to the Firebase cloud back end. Data in Firebase stored in JSON tree.
   The private features of Firebase database work in a combination of FirebaseAuth and authorized users. The public values can be accessed without authentication depending on database rules. So, you can restrict access to the parts of the database with registered users.     

Read data from Firebase: Firebase is a back-end service provider (BaaS) that provides database, authentication, and cloud storage services, Once you create an application on the Firebase console, and choose the Real-Time Databases.  Then, set the security rules. Finally, configure the Firebase into your app by,

import React from “react”;
Import Firebase from “Firebase”
import config from “./config”

In the config.js, you can put your credentials that contain,
Const config = {
apiKey: “{your key}”
authDomain: “{your Key}”
database URL: “{your Key}” 

export default config 

Creating an application:
 First, initialize the Firebase app in the constructor. 

class App extends React.Component {
constructor(props){
    super(props)
    Firebase.InitializeApp(config.Firebase);

     this.state = {
        employees:[]
}
}
Then write the logic for getting and saving data. writeUserdata will write our state into the database, The getUserdata will create a listener on/path, and on-values 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 into componentDidUpdate. Then put the getUserData into ComponentDidMount as, 

    ComponentDidMount () {
        this.getUserData();
     }

    componentDidUpdate(preProps, prevState) {
       if ( prevState !== this.state) {
            this.writeUserData();
        }
    }
Now we will map our employee array from state and put each item in a card component. Each card have delete and update button. When the user clicks the delete button, we will filter out a specific item and delete. Similarly, when the update is clicked, we will get the item data into the form.

Comments