DEV Community

Cover image for How to Fetch and Write data into firestore cloud. Beginners Guide.
Adeeko Tobiloba Isreal
Adeeko Tobiloba Isreal

Posted on

How to Fetch and Write data into firestore cloud. Beginners Guide.

Introduction

Are you tired of keeping your data scattered across multiple platforms and devices? Do you want to streamline your data management process and access all your information in one place? Look no further than Firestore Cloud! With Firestore, you can easily store and manage your data in the cloud, and access it from anywhere at any time. In this beginner's guide, we'll show you how to fetch and write data into Firestore Cloud, step-by-step.

Table of content

  1. Setup Firebase for your project.
  2. Setup your react project
  3. Connect and Initialize Firebase to your project
  4. Create Firestore Database in your firebase console.
  5. Write data to your firestore cloud
  6. Read data from your firestore cloud

Setup Firebase for your project: This is one of the most crucial yet basic part of setting up your firebase console for your application. So in other to make things easy. I'll walking you through images of each step on how to setup firebase console for your application.

step 1: Go to Firebase Link. Sign up and login to firebase. So that your console can be created.

step 2:
Image description
Now that you have your console setup. You can proceed to click on the Add Project box to get started with initiating your project.

step 3:
Image description
As shown in the image follow the prompt by adding the name of the project you chose. As for me attendance-app works fine.

step 4:
Image description
So this page explains the features you'll be getting on your console for free. Nothing much to see here though. Just to fulfill all righteousness i gotta include it. Click continue let's get on with this 😎.

step 5:
Image description
Click the dropdown and select the Default account for firebase then continue.

step 6:
Image description
Cool.. We're getting very close to the cool stuff. Our app console has been successfully created on firebase.

Not assuming you already have a project setup yet.
You can easily setup your react project by using this command in your terminal
npx create-react-app attendance-app. There are other frameworks out there that you can also use to with firebase. Which are Vuejs, Nextjs, Angularjs... and any other frontend framework you know about. Its not quantum physics to set firebase up with any of them, pretty much similar steps to follow.

In this article we're going to be using a react project.

After creating your application in your terminal.
Navigate to the folder in which you have created your project and open it in vscode or which ever IDE you're using. My favorite is Vscode though.

Setup your react project: Now take a sneak peak of the folder structure of one of the react projects. I'm working on.

Image description
In this image you'll notice there is a firebase.js file in there. Yes this is where firebase is being connected to your project. To get started on that you have to follow these steps.

  1. Go to your firebase console.
  2. Click on the settings icon next to Project Overview on the left pane of your firebase console dashboard.
  3. Click on project settings and scroll to the bottom of the page. You'll find a detailed set on how to add firebase to your project.
  4. Open your terminal and navigate to your project directory.
  5. Type npm install firebase to have it installed in your project.
  6. Then create a firebase.js file.
  7. Add this code in the firebase file.
//Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
 //TODO: Add SDKs for Firebase products that you want to use
 //https://firebase.google.com/docs/web/setup#available-libraries`

 //Your web app's Firebase configuration
 //For Firebase JS SDK v7.20.0 and later, measurementId is optional
 const firebaseConfig = {
  apiKey: "******************************",
  authDomain: "******************************.firebaseapp.com",
  projectId: "attendance-app-******************************,
  storageBucket: "******************************.appspot.com",
  messagingSenderId: "***********",
  appId: "1:******************************",
  measurementId: "******************************"
  };

  //Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
Enter fullscreen mode Exit fullscreen mode

You'll find the necessary data i excluded from this code block in your firebase console.

Create Firestore Database in your firebase console: To do these we'll be going through another set of graphics to better visualize our steps.
a.
Image description
..Click on build on the left panel
..Click on Firestore Database as highlighted in the image above.
..Click on the create database button, then you'll be prompted to setup in production in a modal.
..Click on the closest location to you and hit continue button.

Image description

Then you'll have a view of your database.
Kindly read up on firestore rules as you might need it for specific functions in your database. Firestore Rules

Writing Data to your database Firestore

Firstly you have to reference the database in any file you want to initialize the write data function

import { getDatabase } from "firebase/database";

const database = getDatabase();
Enter fullscreen mode Exit fullscreen mode

This function below allows you to write data into your firestore database

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

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture : imageUrl
  });
}
Enter fullscreen mode Exit fullscreen mode

Reading Data from your database Firestore

Firstly you have to reference the database in any file you want to initialize the read data function

import { getDatabase } from "firebase/database";

const database = getDatabase();
Enter fullscreen mode Exit fullscreen mode
import { getDatabase, ref, child, get } from "firebase/database";

const dbRef = ref(getDatabase());
get(child(dbRef, `users/${userId}`)).then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("No data available");
  }
}).catch((error) => {
  console.error(error);
});
Enter fullscreen mode Exit fullscreen mode

You can also read the firebase documentation for your reference. https://firebase.google.com/docs/database/web/read-and-write?hl=en&authuser=0

Thank you for going this far. Like and drop comments if this was helpful, and i'm open to questions or constructive criticism.

Have a bug-filled day 😃

Top comments (0)