How to use Firebase Realtime Database in React App?

What is a Firebase Realtime Database?

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.

// Get a reference to the database service
var database = firebase.database();

Basic write operations

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}

Read data once

var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
  var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
  // ...
});

Reference – Firebase Docs – https://firebase.google.com/docs/database/web/read-and-write?authuser=0

CSS Cheat Sheet

Flexbox

display: flex;
flex-direction: column/column-reverse/row/row-reverse;
flex-wrap: wrap/nowrap/wrap-reverse;
justify-content: center/flex-start/flex-end/space-around/space-between;
align-items: flex-start/flex-end/center/stretch/baseline;
align-content: space-between/space-around/stretch/center/flex-start/flex-end;

Perfect Centering

div {
 display: flex;
 height: 300px;
 justify-content: center;
 align-items: center;
}

Gradient

background-image: linear-gradient(direction, color1, color2);
background-image: linear-gradient(to right/to left, white, grey);

Reference – https://www.w3schools.com/css/css3_gradients.asp

Border-Radius

border-bottom-right/bottom-left/top-right/top-left: 10px;

Image Maps

<img src="workplace.jpg" alt="Workplace" usemap="#workmap">

<map name="workmap">
  <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
  <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
  <area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>

Box-Shadow

box-shadow: 5px(down) 10px(right) red(color);

CSS Media Queries

@media screen and (min-width: 480px) {
 body {
       background-color: blue;
 }
}

If viewport/view area is larger than 480px in the case above, background-color will change to blue.

max-width: 480px will change the color when viewing area is lesser than mentioned.

Dead Frontier : MMO

Dead Frontier is an amazing MMO game with thousands of players in real-time. There are loads of weapons and items to loot in the city and buy from the marketplace.

https://www.deadfrontier.com/

This is my profile on DF

Here’s the Boss Map – https://bossmap.dfprofiler.com/

Resources – http://www.dfprofiler.com/

Dead Frontier Wiki – https://deadfrontier.fandom.com/wiki/Dead_Frontier_Wiki

Discord Server – https://discord.com/channels/429253210990182406/430042463328272386

Module build failed: Error: Cannot find module ‘babel-core’

Below error could show up after installing dependencies to a project from Package.json. For babel specific dependency, we might have to install separate babel/core to resolve this issue.

./src/index.js
Module build failed: Error: Cannot find module 'babel-core'
Require stack:
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\babel-loader\lib\index.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\loader-runner\lib\loadLoader.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\loader-runner\lib\LoaderRunner.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\webpack\lib\NormalModule.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\webpack\lib\NormalModuleFactory.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\webpack\lib\Compiler.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\webpack\lib\webpack.js
- C:\Users\jayes\Downloads\the_venue\the_venue\node_modules\react-scripts\scripts\start.js
npm install --save-dev @babel/core @babel/preset-env

Reference – https://github.com/babel/gulp-babel/issues/124#issuecomment-326853222

All Hail, Babel!

How to deploy React App to Firebase?

Steps to deploy the app to Firebase:

npm install -g firebase-tools
PS C:\Users\jayesh\Documents\React-September> npm install -g firebase-tools

C:\Users\jayesh\AppData\Roaming\npm\firebase -> C:\Users\jayesh\AppData\Roaming\npm\node_modules\firebase-tools\lib\bin\firebase.js

+ firebase-tools@8.10.0
updated 1 package in 32.755s
firebase login
PS C:\Users\jayesh\Documents\React-September\Venue Website Udemy\sep-venue-app> firebase login

Already logged in as <yourfirebaseaccount@gmail.com>
firebase init
PS C:\Users\jayesh\Documents\React-September\Venue Website Udemy\sep-venue-app> firebase init

You're about to initialize a Firebase project in this directory:

C:\Users\jayesh\Documents\React-September\Venue Website Udemy\sep-venue-app

? Are you ready to proceed? Yes
? Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. 
 ( ) Database: Deploy Firebase Realtime Database Rules
 ( ) Firestore: Deploy rules and create indexes for Firestore
 ( ) Functions: Configure and deploy Cloud Functions
>(*) Hosting: Configure and deploy Firebase Hosting sites
 ( ) Storage: Deploy Cloud Storage security rules
 ( ) Emulators: Set up local emulators for Firebase features
First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

i  .firebaserc already has a default project, using bhiyaoo-4b9fe.

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

? What do you want to use as your public directory? build
? What do you want to use as your public directory? build
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? File build/index.html already exists. Overwrite? (y/N) No

i  Writing configuration info to firebase.json...

+  Firebase initialization complete!
firebase deploy

PS C:\Users\jayesh\Documents\React-September\Venue Website Udemy\sep-venue-app> firebase deploy

=== Deploying to 'bhiyaoo-4b9fe'...

i  deploying hosting
i  hosting[bhiyaoo-4b9fe]: beginning deploy...
i  hosting[bhiyaoo-4b9fe]: found 20 files in build
+  hosting[bhiyaoo-4b9fe]: file upload complete
i  hosting[bhiyaoo-4b9fe]: finalizing version...
+  hosting[bhiyaoo-4b9fe]: version finalized
i  hosting[bhiyaoo-4b9fe]: releasing new version...
+  hosting[bhiyaoo-4b9fe]: release complete

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/bhiyaoo-4b9fe/overview
Hosting URL: https://bhiyaoo-4b9fe.web.app

App will be hosted at URL provided by Firebase Hosting.

Reference – How to deploy a React application to Firebase by ROBIN WIERUCH – https://www.robinwieruch.de/firebase-deploy-react-js

Keep Hosting! 🎇

What is dotenv and how to use it?

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

https://github.com/motdotla/dotenv

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

process.env now has the keys and values you defined in your .env file.

const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Happy Rusev Day!

Ways to create Forms in React

There are certain ways using which we can create Forms in ReactJS. One is using Class Components and another using Functional Components using Hooks.

Forms created using Class Component:

import React, { Component } from "react";

class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Form;

Forms can be created using React Hook Form – Functional Component

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = (data) => console.log(data);

  console.log(watch("example"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>

      <input name="exampleRequired" ref={register({ required: true })} />

      {errors.exampleRequired && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

Keep Creating!

Gardening in Quarantine

Doing something new has always inspired me. During the lockdown of Covid-19 Coronavirus pandemic, I tried again. This time, Gardening. Fresh vegetables, organic. The joy of seeing plant grow from nothing to something big is amazing.

I am sharing a video in the bottom of this post created from my garden. Along with my mother, I have been taking care of the vegetable garden. Have a look and let me know if it is exciting.

Fresh and Organic Lady Finger and Baby Snake Gourd
Fenugreek leaves fresh outta garden!
Check this video out!

Keep Eating, Folks 🥕