Firebase Real-Time Database in React.

What is firebase real-time database?

Firebase real-time database is a cloud-hosted NoSQL database. In this database, data is stored in the object(JSON) format and synchronized in real-time to all connected clients.

All the connected clients will receive the latest updates with the latest data.


Getting started with Firebase real-time database.

Installation and setup of the real-time database.

1. Create a database

  • Go to the firebase console and navigate to the RealTime Database section and select your existing project ( How to create project ).
  • After selecting of RealTime Database follow the below steps to perform crud operation on the database.
  • Select the mode of your firebase security rules.
    1. Test Mode – Anyone can read and modify the data. Know more about security rules
    2. Locked Mode – Denies from read and write only authenticated applications can access the data.
  • Select the location of the database and click on Done.

2. Configure the real-time database in your project

1 Install firebase using npm.

npm install firebase

2 Initialize the firebase and create a firebase app object.

import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";

const firebaseConfig = {
  // your config object key and value.
};

// Initialize firebase app.
const app = initializeApp(firebaseConfig);

// Initialize firebase database and get the reference of firebase database object.
const database = getDatabase(app);

Read & Write data (CRUD Operations ) on the firebase database.

1. Create Data

Note It reset the data on the specific object reference.

import { getDatabase, ref, set } from "firebase/database";

// Get the reference of the database.
const database = getDatabase();

// Setting the data.
var cartId = 1;
const data = {
   cartId: cartId,
   products: [
      { 
          'title' : 'product1',
          'price': 50
      },
      { 
          'title' : 'product2',
          'price': 30
      },
      { 
          'title' : 'product3',
          'price': 70
      },     
   ],
}
set(ref(database, 'cart/' + cartId), data).then( () => {
   // Success.
} ).catch( (error) => {
  console.log(error);
} );

2. Read the Data in Real-Time Using OnValue()

Note Onvalue() is called every time when data is changed on the specific object reference. Use onValue() to observe events.

This method is triggered once when the listener is attached and every time when data is changed.

import { getDatabase, ref, onValue } from "firebase/database";

// Get the reference of the database.
const database = getDatabase();

const cartRef = ref(database, 'cart/' + cartId);

onValue(cartRef, (snapshot) => {
  const data = snapshot.val();
  if( !!data ) {
    console.log(data);
  } else {
    console.log('Data not found');
  }  
});

3. Read the data once with an observer( OnValue )

import { getDatabase, ref, onValue } from "firebase/database";

// Get the reference of the database.
const database = getDatabase();

const cartRef = ref(database, 'cart/' + cartId);

onValue(cartRef, (snapshot) => {
  const data = snapshot.val();
  if( !!data ) {
    console.log(data);
  } else {
    console.log('Data not found');
  }  
}, {
  onlyOnce: true
});

4. Read data once with get()

import { getDatabase, ref, child, get } from "firebase/database";

// Get the reference of the database.
const database = getDatabase();

get(child(ref(database), 'cart/' + cartId)).then((snapshot) => {
  if (snapshot.exists()) {
    let data = snapshot.val();
    console.log(data);
  } else {
    console.log("Data not available");
  }
}).catch((error) => {
  console.error(error);
});

5. Update data using update()

Note We can also use an update() to delete the data by updating the null value.

import { getDatabase, ref, child, push, update } from "firebase/database";

// Get the reference of the database.
const database = getDatabase();

const updates = {};

updates['cart/' + cartId + '/cartId'] = updatedCartId;
updates['cart/' + cartId + '/products'] = { title: 'updated product', price : 50 };

update(ref(database), updates).then( () => {
  // Success
} ) .catch((error) => {
  console.log(error)
} )

6. Delete data using set()

import { getDatabase, ref, set } from "firebase/database";

// Get the reference of the database.
const database = getDatabase();

set(ref(database, 'cart/' + cartId), null).then(() => {
  // Success
})
.catch((error) => {
  console.log(error);
});

Thanks for reading this article, now you are able to implement the firebase real-time database in your project. Read More


Source link