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

ログインユーザーのプロフィール名を取得して表示

ロジックコード

App.js
  const [profileName, setProfileName] = useState('');
  
useEffect(() => {
  const unsub = onAuthStateChanged(auth, (currentUser) => {
    setUser(currentUser);

    if (currentUser) {
      console.log('ログインユーザーのUID:', currentUser.uid);

      (async () => {
        try {
          const profileDoc = await getDoc(doc(db, 'users', currentUser.uid));
          if (profileDoc.exists()) {
            const data = profileDoc.data();
            setProfileName(data.name || currentUser.displayName || '匿名');
          }
        } catch (err) {
          console.warn("プロフィール情報の取得に失敗しました", err);
        }
      })();
    }
  });
  return () => unsub();
}, []);

UIコード

App.js
         {profileName}
        </span>さ      </p>

・onAuthStateChanged によってログイン状態を監視。
・ユーザーがログインしていたら、currentUser.uid を使って Firestore の users コレクションからドキュメントを取得。
・users/{uid} から name を取得し、なければ displayName、それもなければ "匿名" を表示名とする。

投稿一覧のユーザー名をFirestoreのusersコレクションから取得して表示

ロジックコード

App.js
useEffect(() => {
  const fetchPosts = async () => {
    try {
      const postsCollection = collection(db, 'posts');
      
    // 	Firestoreのpostsコレクションから、すべての投稿ドキュメントを取得します。
	// 	snapshot.docsでドキュメント配列を取得できます。
      const snapshot = await getDocs(postsCollection);

      const postsData = await Promise.all(snapshot.docs.map(async (docSnap) => {
        const postData = docSnap.data();
 
    //	postData.uid(投稿者のUID)を使って、users/{uid} というドキュメントを取得。
	//	このusersコレクションには、プロフィールのnameやphotoURLが保存されていると想定されます。
        const userDoc = await getDoc(doc(db, 'users', postData.uid));

	//	投稿時に保存された displayName を初期値とします。
	//	userDoc が存在していれば、そこから userData.name を取り出し、投稿に表示する名前として上書きします。
        let nameFromUserCollection = postData.displayName; // 投稿保存時の名前を初期値として使用
        if (userDoc.exists()) {
          const userData = userDoc.data();
          nameFromUserCollection = userData.name || nameFromUserCollection;
        }

        return {
          id: docSnap.id,
          ...postData,
          displayName: nameFromUserCollection,
        };
      }));

	//	投稿一覧に表示されるデータとして、プロフィールから取得したdisplayNameを含めた投稿情報をReactの状態に保存。
      setPosts(postsData);
    } catch (err) {
      console.error("Error getting posts:", err);
    }
  };

  fetchPosts();
}, [setPosts]);

UIコード

<p className="font-semibold text-sm">{post.displayName}</p>

・ここで表示される post.displayName は、上記ロジックによって users/{uid} から取得された name に基づいています。

Firestore

スクリーンショット 2025-05-15 9.54.08.png

UI

スクリーンショット 2025-05-15 9.51.43.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?