
Firebase
【Firebase】Firestore Databeseの単一データを取得し、フロントエンドに表示する
作成日:2022年02月05日
更新日:2022年02月06日
前回は、Firestore Databese のデータを、フロントエンドに表示しました。

【Firebase】Firestore Databeseのデータを、フロントエンドに表示する
今回は、Firestore Databese の単一データを所得し、フロントエンドに表示します。
単一データが取得できたかわかるように、Firestore Database にデータを追加しました。
まずは、先日作成した BooksGet.js の内容をコピーし、編集します。
jsx
import React, { useState, useEffect } from "react";
import { firebaseApp } from "../firebase/firebaseConfig";
const BookGet = () => {
const [book, setBook] = useState([]);
useEffect(() => {
const firestore = firebaseApp.firestore;
getBook();
}, []);
return (
<div>
<p>{book.title}</p>
<p>{book.author}</p>
<p>{book.category}</p>
</div>
);
};
export default BookGet;
useEffectの中で async/await が使えるようにします。
jsx
useEffect(() => {
const firestore = firebaseApp.firestore;
const getBook = async () => {};
getBook();
}, []);
firebase/firestore からgetDocとdocをインポートします。
jsx
import { getDoc, doc } from "firebase/firestore";
docを使って、単一データを指定しましょう。
jsx
const getBook = async () => {
const docRef = doc(firestore, "Books", "OriihusPZx14s2Equ5fg");
};
単一データを取得するために、getDocを使います。
jsx
const getBook = async () => {
const docRef = doc(firestore, "Books", "OriihusPZx14s2Equ5fg");
const docSnap = await getDoc(docRef);
};
docSnapのdata()をsetBookで状態管理します。
一通り完了したので、ブラウザで確認すると、
ID で指定したデータのみ取得することができました。
単一データを取得できています。
次回は、Firestore Databese のデータベースを、リアルタイムで取得します。

【Firebase】Firestore Databeseのデータを、リアルタイムで取得する
お知らせ

私事ですが、Udemyで初心者を対象にしたReactの動画コースを作成しました。
Reactについて興味がありましたら、ぜひ下のリンクからアクセスしてください。
詳しくはこちら(Udemyの外部サイトへ遷移します)