본문 바로가기

Backend/Firebase

Firebase Database (Angular, React)

반응형

Firebase is a cloud-based backend service that provides various features. For the database services, there are real-time databases, an older version, and a newer version called Firestore. Since there is not much of a difference between the two we will see how we can set up, and use the Firestore with applications

List of Contents

Firestore Service

Creating a Service

From the left menu click Build -> Firestore Database

Click Create database

Select a mode (production mode is a safer option but not suitable for the development environment). This can be changed later.

Choose location

Adding Data

Select Start collection

Add a collection name (same as the table name in the relational database)

Fill in the in-fields. Click 'Auto-ID' to create an id

To add data, click Add document

Rules

By default, anyone can access, update, and delete the data. To change this use the rules

▶ Normal Data

For example, if you want only logged-in users to update and delete a post, we can set the rule as follows

match /<tableName>s/{<tableName>} {
  allow read;
  allow create: if request.auth != null;
  allow delete: if resource.data.userRef == request.auth.uid;
  allow update: if resource.data.userRef == request.auth.uid;
}

▶ Auth Data

For the authentication, only the update and deletion need to check if the person is the right user. So we can set the rule like this

match /<tableName>s/{<tableName>} {
  allow read;
  allow create;
  allow update: if request.auth.uid == <tableName>;
  allow delete: if request.auth.uid == <tableName>;
}

Indexes (for queries)

Some queries need an index to work. Select indexes

Add a collection name and at least two fields that will be the conditions

Check the collection and click save

Working with Applications

 

Firebase - Connecting to Applications

Firebase is Google's backend cloud service that provides a database to store data, authentication, hosting, and so on. The main advantage of using a cloud service like this is, of course, there is no need to develop a backend (or at least can save a huge a

jin-co.tistory.com

React

▶ Get List (getDocs)

Import necessary functions

import { collection, getDocs } from 'firebase/firestore'
import { db } from '../firebase.config'

Collections in Firestore are the tables for the relational database. To fetch data from Firestore, we need to fetch a collection first. Add the database configuration file and the needed collection as values for the 'collection' function

 

Request data with getDocs asynchronously and use '.data()' to get the data from the fetched document

const [listings, setListings] = useState(null)
const [loading, setLoading] = useState(true)

useEffect(() => {
  fetchListings()
}, [])

const fetchListings = async () => {
  try {
    const listingRef = collection(db, 'listings')
    const docSnap = await getDocs(listingRef)
    const listings = []    
    docSnap.forEach((doc) => {      
      listings.push({
        id: doc.id,
        data: doc.data()
      })
    })
    setListings(listings)
    setLoading(false)
  } catch (error) {
    // error handling
  }
}

▶ Adding Queries

We can add queries using the query function

 

Import necessary functions

import { collection, getDocs, query, where, orderBy, limit, startAfter } from 'firebase/firestore'
import { db } from '../firebase.config'

Pass the fetched collection a value with the queries to the query function (Certain queries such as orderBy require indexing)

const [listings, setListings] = useState(null)
const [loading, setLoading] = useState(true)

useEffect(() => {
  fetchListings()
}, [])

const fetchListings = async () => {
  try {
    const listingRef = collection(db, 'listings')
    const q = query(
      listingRef,
      where('type', '==', params.categoryName),
      orderBy('timestamp', 'desc'),
      limit(10)
    )
    const docSnap = await getDocs(q)
    const listings = []    
    docSnap.forEach((doc) => {      
      listings.push({
        id: doc.id,
        data: doc.data()
      })
    })
    setListings(listings)
    setLoading(false)
  } catch (error) {
    // error handling
  }
}

▶ Get Item (getDoc)

Import necessary functions

 

import { getDoc, doc } from 'firebase/firestore'
import { getAuth } from 'firebase/auth'
import { db } from '../firebase.config'

Use getDoc asynchronously

const docSnap = await getDoc(docRef)
if (docSnap.exists()) {
  setListing(docSnap.data())  
}

▶ Add (addDoc)

Import necessary functions

 

import { addDoc, collection, serverTimestamp } from 'firebase/firestore'

Use addDoc asynchronously

const [formData, setFormData] = useState({
  name: '',
})

await addDoc(collection(db, 'listings'), formData)

Use serverTimestamp to add created time

const [formData, setFormData] = useState({
  name: '',
})

const formDataCopy = {
  ...formData,
  timestamp: serverTimestamp()
}

await addDoc(collection(db, 'listings'), formDataCopy)

▶ Update (updateDoc)

Import necessary functions

 

import {
  addDoc,
  collection,
  serverTimestamp,
  doc,
  updateDoc,
  getDoc,
} from 'firebase/firestore'

Use updateDoc asynchronously

const [formData, setFormData] = useState({
  type: 'rent',
  name: '',
  bedrooms: 1,
  bathrooms: 1,
  parking: false,  
})
  
const docRef = await doc(db, 'listings', params.listingId)
await updateDoc(docRef, formData)

▶ Delete (deleteDoc)

Import necessary functions

 

import {
  addDoc,
  collection,
  serverTimestamp,
  doc,
  updateDoc,
  getDoc,
} from 'firebase/firestore'

Use deleteDoc asynchronously

await deleteDoc(doc(db, 'listings', id))

In this writing, we have seen Firestore service in the Firebase to work with data.


References

Firebase Realtime Database (google.com)

 

Firebase Realtime Database

NoSQL 클라우드 데이터베이스로 데이터를 저장하고 동기화하세요. 모든 클라이언트에서 실시간으로 데이터가 동기화되고 앱이 오프라인일 때도 데이터를 사용할 수 있습니다.

firebase.google.com

 

728x90
반응형