Firestoreのデータ取得方法まとめ

● Firestore データの取得方法

データ取得方法は以下の3種類

・getDoc()   「単一のドキュメントを取得」
・getDocs() 「コレクション(複数のドキュメント)を取得」
・onSnapshot() 「コレクション(複数のドキュメント)をサブスクライブし、中のドキュメントのどれかに変更がある場合自動的に全てのコレクションを自動で再読込(購読件数分の再リクエストが発生します)」

の3種類です。

公式 : https://firebase.google.com/docs/firestore/query-data/get-data?hl=ja

・getDoc

getDoc() メソッドに「ドキュメントリファレンス」を突っ込みます

import { doc, getDoc } from "firebase/firestore"

const docRef = doc(db, "cities", "MY-ID")
const docSnap = await getDoc(docRef)

console.log( '● 取得したデータ' )
console.log( docSnap.data() )

なお、docRefはコレクションリファレンスからも作成できます。

const docRef = doc(db, 'cities', 'MY-ID')

  ↓ このように記述することができます

const colRef = collection(db, 'cities')
const docRef = doc(colRef, 'MY-ID')

・getDocs

getDocs() メソッドに「コレクションリファレンス」を突っ込みます

import { getDocs, collection, DocumentData } from 'firebase/firestore'

const [users, setUsers] = useState<DocumentData[]>([])

const colRef = collection(firebaseDB, 'users')
const querySnapshot = await getDocs(colRef)
setUsers(querySnapshot.docs.map(doc => doc.data()))

・onSnapshot

import { getDocs, onSnapshot, query } from 'firebase/firestore'
import DocumentData = firebase.firestore.DocumentData

const [users, setUsers] = useState<DocumentData[]>([])

const q = query(collection(firebaseDB, 'users', user.uid, 'transactions'))
await onSnapshot(q, snapshot => {
  setUsers(snapshot.docs.map(doc => doc.data()))
})

JSX

<div>
  <h1>getDocs</h1>
  {users.map((user, i) => {
    return <div key={i}>{user.name}</div>
  })}
</div>

● withConverter を指定してデータ取得時に自動でコンバートする

const docRef = doc(colRef, 'MY-ID')

 ↓ withConverter メソッドを追加します

const docRef = doc(colRef, 'MY-ID').withConverter(myFirestoreConverter)

公式 : https://firebase.google.com/docs/reference/js/v8/firebase.firestore.FirestoreDataConverter


● react-query を使用して取得する

以下の中から必要なパッケージをインストールします。

@react-query-firebase/analytics
@react-query-firebase/auth
@react-query-firebase/database
@react-query-firebase/firestore
@react-query-firebase/functions

yarn add @react-query-firebase/auth @react-query-firebase/firestore


● react-firebase-hooks を使用して取得する

https://github.com/CSFrequency/react-firebase-hooks

import { useCollection } from 'react-firebase-hooks/firestore'

const dbQuery = query(collection(firebaseDB, 'users'))
const [value, loading, error] = useCollection(dbQuery)

jsx

<div>
  <h1>react-firebase-hooks</h1>
    {error && <strong>Error: {JSON.stringify(error)}</strong>}
    {loading && <span>Loading...</span>}
    {value && (
      <ul>
        {value.docs.map(doc => (
          <li key={doc.id}>
            <strong>{doc.id}</strong> : {JSON.stringify(doc.data())},{' '}
          </li>
        ))}
      </ul>
    )}
</div>

https://github.com/CSFrequency/react-firebase-hooks/tree/v4.0.2/firestore#full-example

No.2228
10/27 16:15

edit