CRUD operations using firebase

By Prajwal Haniya

Tech-letter #3 | December 24,2022

  1. What are microservices?

    Over the past few weeks, I am learning about microservices. We are implementing microservice architecture and shifting from a monolithic repo. So, understanding microservices in turn can help you with understanding the scalability and performance of your application.

    So what’s really a microservice?

    A microservice allows you to group APIs and services separately in a component-like structure and run individual components in a dedicated server. So that if any service goes down, it won’t affect the entire application. Mostly it is completely the backend architecture for easier development and scalability.

    Some of the advantages of microservices are:

    • Highly maintainable
    • Can be deployed independently
    • Owned by individuals or a small team.

    Some of the disadvantages of microservices are:

    • Difficult to debug
    • Difficult to maintain the records of which service is maintained by whom if the business and codebase grow.
    • Communication within the team can be slower.

    You can know more about microservices here

  2. How to connect your react application to the firebase real-time database?

    Firebase makes your backend roll up quickly. You don’t need to write any config file, APIs, or services. So, here is the basic file, which you must include inside the src/utils folder

    import { initializeApp } from "firebase/app";
    import { getDatabase } from "firebase/database";
    
    const firebaseConfig = {
        apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
        authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
        databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
        projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
        storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
        messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
        appId: process.env.REACT_APP_FIREBASE_APP_ID,
        measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
    };
    
    const app = initializeApp(firebaseConfig);
    export const db = getDatabase(app);
    

    Use the above file in your application. Make sure to paste all your credentials in a .env file . Using .env file is the best practice, so that you won’t expose your credentials while committing the code to your repo.

  3. How to create & delete the data from the firebase realtime database in react?

    // make sure to import db & ref 
    import { db } from '../../utils/firebase';
    import { set, ref, remove } from 'firebase/database';
    
    // ... all your code
    
    const createHandler = () => {
        let obj = {
            name: 'Praj',
            language: 'JavaScript'
        }
            // set is used to create data passed in terms of object
        set(ref(db, 'posts/' + uuidv4()), obj);
    }
    
    const deletePostHandler = () => {
        const data = ref(db, 'posts/' + id);
            // remove is used to remove data
        remove(data);
    }
    
  4. How to retrieve the data from the firebase real-time database?

    The below code fetches the data from the ‘posts’ that you have created above. Remember, the data will be fetched in an object format: [{{}, {}}] . So you can’t just map and render the data on the screen. But, you can use forEach for that purpose, and how to use forEach? You can find the solution to this question below.

    const getData = () => {
    	const data = ref(db, 'posts')
      onValue(data, (snapshot) => {
          setRetrievedPosts(snapshot.val());
    	})
    }
    
  5. How to use forEach for the retrieved data from the real-time database?

    The data that you fetch from the realtime database will be in the format of Object of Objects that is {{}, {}} so you won’t be able to map as we normally do to array of objects. A different method is given below.

let results = [];
Object.keys(retrievedPosts).forEach((item, index) => {
    results.push(
        <YourComponent 
            item={item}  
        />
    )
})

// then call the results inside the jsx
	return (
		<div>
			{results}
		</div>
	)