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

ロジックコード

✅ 1. インポート

PostPage.js
import React, { useState } from 'react';
import Header from './Header';
import { db, storage } from './FireBase';
import { collection, addDoc, doc, getDoc } from 'firebase/firestore';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { useNavigate } from 'react-router-dom';

• 必要なライブラリやFirebaseの機能をインポート。
• useNavigate は投稿後にホーム画面へ遷移するのに使われます。

✅ 2. コンポーネント定義と受け取るprops

PostPage.js
function PostPage({ profilePhotoURL, profileName, user, setUser }) {

• user:現在ログイン中のユーザー情報
• setUser:ユーザー状態の更新関数(今回は未使用でも将来のため渡している)
• profilePhotoURL, profileName はHeaderに渡すために使う(投稿時には使っていない)

✅ 3. 状態管理

PostPage.js
const [text, setText] = useState('');
const [image, setImage] = useState(null);
const [video, setVideo] = useState(null);
const [showPostForm, setShowPostForm] = useState(true);
const navigate = useNavigate();

• text: 投稿テキスト
• image: 投稿画像(1つだけ)
• video: 投稿動画(1つだけ)
• showPostForm: 投稿フォームの表示切り替え
• navigate: ページ遷移用フック

✅ 4. 投稿処理のメイン関数:handleSubmit

PostPage.js
  if (!user || !user.uid) {
    alert("ログインしていません。投稿できません。");
    return;
  }

  if (text.trim() === '') return;

• 未ログインなら投稿不可
• テキストが空なら投稿処理を行わない

🔹 バリデーションチェック

PostPage.js
  if (!user || !user.uid) {
    alert("ログインしていません。投稿できません。");
    return;
  }

  if (text.trim() === '') return;

• 未ログインなら投稿不可
• テキストが空なら投稿処理を行わない

🔹 時刻の整形

PostPage.js
  const now = new Date();
  const formattedTime = now.toLocaleString('ja-JP', { ... });

• 日本の形式で日時を記録(例:2025/05/24 13:45)

🔹 画像・動画のFirebase Storageへのアップロード

PostPage.js
if (image) {
  const safeFileName = ...
  const imageRef = ref(storage, `images/${safeFileName}`);
  const snapshot = await uploadBytes(imageRef, image);
  imageUrl = await getDownloadURL(snapshot.ref);
}

• ファイル名に特殊文字が入っていても安全なように変換
• アップロード後にStorageのURLを取得

同様に動画も処理されます。

🔹 Firestoreからプロフィール情報の取得

PostPage.js
const profileDoc = await getDoc(doc(db, 'users', user.uid));

• users コレクションからログイン中のユーザーの名前や写真を取得
• なければ Firebase Authentication の displayName か photoURL を使用

🔹 Firestoreへの投稿データ保存

PostPage.js
const newPost = { ... };
await addDoc(collection(db, 'posts'), newPost);

• 投稿内容をオブジェクトにまとめて posts コレクションに保存

🔹 成功時処理

PostPage.js
alert("投稿しました!");
setText('');
setImage(null);
setVideo(null);
navigate('/');

• 投稿完了メッセージ
• フォームを初期化
• ホーム(/)へ遷移

✅ 5. JSXの描画部分

PostPage.js
<Header ... />

• Headerにはuserやプロフィール画像、名前を渡している

PostPage.js
{user ? (
  showPostForm && (
    <form onSubmit={handleSubmit}> ... </form>
  )
) : (
  <div>投稿するにはログインしてください</div>
)}

• ログインしていれば投稿フォームを表示
• 未ログインなら注意メッセージを表示

投稿フォームの中身

PostPage.js
<textarea ... />
<input type="file" ... />
<button type="submit">投稿する</button>

• 投稿文を入力するエリア
• 画像または動画をアップロードできるファイル入力欄(画像と動画は排他)
• 投稿ボタン

PostPage.js
export default PostPage;

• このコンポーネントを他のファイルから使えるようにエクスポート

ルーティングコード

AppRouter.js
<Route path="/post" element={<PostPage user={user} setUser={setUser} />} />

PostPage内でuserが使えるようにする。

UI

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