0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ChatGPTを使用したアプリ開発記【プロフィール画面に詳細情報を表示】

Posted at

UIコード

Profile.js
        {profile ? (
          <div className="bg-white p-4 rounded-lg shadow-md">
            {profile.photoURL && (
              <img
                src={profile.photoURL}
                alt="プロフィール画像"
                className="w-24 h-24 rounded-full mb-4"
              />
            )}
            <p><strong>名前</strong>{profile.name}</p>
            <p><strong>自己紹介</strong>{profile.bio}</p>
          </div>
        ) : (
          <p>読み込み中...</p>
        )}
      </div>

Firestoreからデータを取得するロジック

Profile.js
useEffect(() => {
  const fetchUserProfile = async () => {
    try {

    // db: これは Firestore のデータベースインスタンスです。import { db } from './FireBase' のようにインポートされているはずです。
	// doc(): これは Firestore の doc メソッドで、指定したコレクション(ここでは 'users')とドキュメント ID(ここでは userId)を使って、特定のドキュメントへの参照を作成します。
	// userId: この値は現在表示しているユーザーの ID です。例えば、userId = 'abc123' のように渡されます。
      const userRef = doc(db, 'users', userId);

      	// getDoc(): これは Firestore の getDoc メソッドで、指定したドキュメント参照(ここでは userRef)からデータを取得する非同期関数です。このメソッドはドキュメントのスナップショット(DocumentSnapshot)を返します。
	// await: getDoc は非同期操作なので、await を使ってデータの取得が完了するまで待機します。
	// userRef: 先ほど作成した、users コレクションの特定のユーザーに対応するドキュメントへの参照です。
	// { source: isOnline ? 'default' : 'cache' }: このオプションは、データの取得方法を指定します。
	// source: データをどこから取得するかを指定するオプションで、'default'(通常のデータ取得)か 'cache'(オフラインキャッシュからのデータ取得)を選べます。
	// isOnline: ネットワーク接続がオンラインかどうかを確認するフラグで、オンラインの場合は通常のデータ取得を行い、オフラインの場合はキャッシュから取得します。
      const userSnap = await getDoc(userRef, { source: isOnline ? 'default' : 'cache' });

      if (userSnap.exists()) {
        setProfile(userSnap.data()); // ← name や bio を含むオブジェクトをセット
      } else {
        setProfile({ name: '未設定', bio: 'プロフィールが設定されていません' });
      }
    } catch (err) {
      setProfile({ name: '未設定', bio: 'オフライン中です' });
    }
  };

  if (userId) {
    fetchUserProfile();
  }
}, [userId]);

Firestoreの構成

スクリーンショット 2025-05-12 12.53.58.png

UI

スクリーンショット 2025-05-12 12.50.34.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?