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

投稿ページでserverTimestampを取得

PostPage.js
import { serverTimestamp } from "firebase/firestore";

const newPost = {
  uid: user.uid,
  text,
  createdAt: serverTimestamp(), // ← 追加(投稿日時)
  likes: 0,
  user: user.email,
  displayName: resolvedName,
  photoURL: resolvedPhoto,
  imageUrl,
  videoUrl,
  comments: [],
  draftComment: ''
};

投稿一覧取得時に「createdAt」で降順にソート

Home.js
import { collection, getDocs, query, orderBy } from "firebase/firestore";

const fetchPosts = async () => {
  try {
    const postsCollection = collection(db, "posts");
    const q = query(postsCollection, orderBy("createdAt", "desc"));  // ← ここで降順指定
    const snapshot = await getDocs(q);

    setDebugInfo(`Firestore投稿件数: ${snapshot.size} 件`);

    // 以降は同じコードでOK
    const postsData = await Promise.all(snapshot.docs.map(async (docSnap) => {
      //...
    }));

    setPosts(postsData);
    setDebugInfo(prev => prev + `\n読み込み成功: ${postsData.length} 件の投稿を取得`);
    setLoading(false);
  } catch (err) {
    setDebugInfo(`❌ 投稿取得エラー: ${err.message}`);
    console.error("Error getting posts:", err);
  }
};

UI

スクリーンショット 2025-06-01 11.21.54.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?