[Firebase]Firestoreに関するメモ
はじめに
React + TypeScript + Firebaseのデータを取得する方法のメモです。※インデントに関しては、整えるのが大変なので省略させてください。。。すみません。
(VSCodeに貼り付ける等でお願いします。)
データ
データは以下の通りCollection | Foo |
---|---|
Document | (ランダムな文字列) |
Field: Data | text: Test |
- 取得
const getData = () => { firestore .collection('Foo') .get() .then((snapShot) => { // type Data = { id: string, text: string } const dataArray: Data[] = []; snapShot.forEach((doc) => { dataArray.push({ id: doc.id, text: doc.data().text, }); }); // dataに格納する。 setData(dataArray); }); };
アプリケーション起動時にデータを取得する場合、以下の通りです。
useEffect(() => { getLocations(); }, []);
- 追加(Documentを追加する。)
const addData = ( text: string, ) => { firestore .collection('Foo') .add({ text, }) .then(() => { getData(); }); };
- 更新
const changeData = ( id: string, text: string, ) => { firestore .collection('Foo') .doc(id) .update({ text, }) .then(() => { getData(); }); };
- 削除
const removeData = (id: string) => { firestore .collection('Foo') .doc(id) .delete() .then(() => { getData(); }); };
まとめ
結構直感でかけるのではないでしょうか。hooksやContext APIを使うことによって、Reactのみで簡単にアプリケーションが作成できてしまいます。