チャットアプリの作成
参考サイト
(https://qiita.com/shintaroa/items/4268c0cc2e10a49f4fce)
※(https://qiita.com/kazu_developer/items/da94e751d2db784ad0ee)でもできそう
&(https://www.youtube.com/watch?v=VhiH1votwm8&t=51s)でReactNative
firebaseのインストール
npm install firebase
firebaseのプロジェクト作成
Firebaseの公式サイトでプロジェクト(プロジェクト名ChatApp)をつくります
そして、プロジェクト内にWebアプリ(アプリ名ChatApp)をつくります
このアプリではデータベースを使うので、
Cloud Firestoreで「データベースを作成」し、テストモードで開始します
expoディレクトリの作成
npx create-expo-app@latest
firebaseの初期化
import { initializeApp } from 'firebase/app';
const firebaseConfig = { 省略 } // firebaseのコンソールからコピペ
const app = initializeApp( firebaseConfig );
firestoreの初期化
import { getFirestore } from 'firebase/firestore';
const db = getFirestore( app );
firebaseにデータを追加する
(https://firebase.google.com/docs/firestore/manage-data/add-data?hl=ja)
idを手動で決める場合
import { doc, setDoc } from 'firebase/firestore';
const saveTask = async() => {
const data = { title: Date.now().toString(), text: taskText };
await setDoc( doc(db,'town','id1'), data);
}
idを自動生成する場合
import { collection, addDoc } from 'firebase/firestore';
const data = { title: Date.now().toString(), text: taskText }
const docRef = await addDoc( collection(db, 'town'), data);
firestoreからドキュメントを取得する
(https://firebase.google.com/docs/firestore/query-data/get-data?hl=ja)
特定のドキュメントを1つ取得する場合
import { doc, getDoc } from 'firebase/firestore';
const docRef = doc(db, 'town', 'id名');
const docSnap = await getDoc(docRef);
if ( docSnap.exists() ) {
console.log('データ:', docSnap.data());
} else {
console.log('No Such Document!');
}
ドキュメントを複数取得する場合
import { collection, query, where, getDocs } from 'firebase/firestore';
// field内のcapitalが’true’のデータのみを取得
const q = query( collection(db, 'town'), where('capital', '==', true) );
const querySnapshot = await getDocs(q);
querySnapshot.forEach( (doc) => {
console.log(doc.id, "=>", doc.data());
});
コレクション内の全てのドキュメントを取得する場合
import { collection, getDocs } from 'firebase/firestore';
const querySnapshot = await getDocs(collection(db, 'town'));
querySnapshot.forEach( (doc) => {
console.log(doc.id '=>', doc.data());
});