BÀI 20 - EXPO FIREBASE TRONG REACT NATIVE

  1. Cài đặt

# Using npm

expo install firebase

Phiên bản này ít lỗi nè

npm install firebase@9.6.11

2. Config firebase (./Firebase/firebase.js)

import { initializeApp } from 'firebase/app';


const firebaseConfig = {

// ...

};


const app = initializeApp(firebaseConfig);


export { app }

Các thư viện của Firebase sử dụng trong Expo: đây Cái này cũng chính là thư viện của Firebase dùng cho webJS

Tài liệu sử dụng: ở đây

  • import thư viện

import { firebaseConfig } from "../Firebases/firebaseConfig"; // Tự tạo config của dự án nha


import { initializeApp } from 'firebase/app';

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

//import {...} from "firebase/auth";

//import {...} from "firebase/database";

//import {...} from "firebase/firestore";

//import {...} from "firebase/functions";

//import {...} from "firebase/storage";


  • Firebase realtime database

Write new data

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


function storeHighScore(userId, value) {

const db = getDatabase();

const reference = ref(db, 'users/' + userId);

set(reference, {

your_child: value,

});

}

Read data

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


function setupValueListener() {

const db = getDatabase();

const reference = ref(db, 'demo' );

onValue(reference, (snapshot) => {

const value = snapshot.val().value;

console.log("New value: " + value);

});

}

  • Firestore Firebase

Write new data - không tự động tạo id

import { getFirestore, setDoc, doc } from "firebase/firestore";


const firestore = getFirestore();


await setDoc(doc(firestore, "Users", auth.currentUser.uid), {

account: signUp.account,

avatar: signUp.avatar,

email: signUp.email,

last_signin: new Date().getTime(),

location: signUp.location,

time_registration: new Date().getTime(),

verification: signUp.verification

});

Read data - all / source

import { getFirestore, collection, getDocs, query } from "firebase/firestore";

const store = getFirestore();

const queryUser = query(collection(store, "Users/"));

const querySnapshot = await getDocs(queryUser);

querySnapshot.forEach(item => {

if (auth.currentUser.uid == item.id) {

setSelectedLocation(item.data().location);

}

});