0
1

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を使用したアプリ開発記【プロフィール画面に投稿内容を表示】

Last updated at Posted at 2025-05-07

1. 投稿データ用Contextを作成

PostContext.js
// Reactライブラリから、Contextを作るcreateContextと状態管理に使うuseStateをインポートしています。
import React, { createContext, useState } from 'react';

// アプリ全体で共有するための「投稿データのコンテキスト」を作成します。PostContext.Providerを使って値を渡します。
export const PostContext = createContext();

// PostProviderというコンポーネントを定義。アプリ全体をこのProviderで包み、投稿データをグローバルに管理できるようにします。
export const PostProvider = ({ children }) => {

// 投稿データ(配列)をpostsとして定義。setPostsで投稿を追加・更新できます。初期値は空の配列です。
  const [posts, setPosts] = useState([]);

// 子コンポーネント(children)すべてにpostsとsetPostsを提供しています。これでどのコンポーネントからでも投稿データにアクセスできます。
  return (
    <PostContext.Provider value={{ posts, setPosts }}>
      {children}
    </PostContext.Provider>
  );
};

2. AppRouter.jsでContextをラップ

AppRouter.js
import { PostProvider } from './PostContext';
import App from './App';
import Profile from './Profile';
import {
  BrowserRouter as Router,
  Routes,
  Route
} from 'react-router-dom';


// ルーティング全体をPostProviderで囲み、投稿データをアプリ全体に共有できるようにします。
function AppRouter() {
  return (
    <PostProvider>

//  /にアクセスすればAppコンポーネントが、/profile/:userIdならProfileコンポーネントが表示されます。
      <Router>
        <Routes>
          <Route path="/" element={<App />} />
          <Route path="/profile/:userId" element={<Profile />} />
        </Routes>
      </Router>
    </PostProvider>
  );
}
export default AppRouter;

3. App.jsでContextを使って投稿管理

App.js
// ReactのuseContextを使って、PostContextの中身(投稿データ)を取得します。
import { useContext } from 'react';
import { PostContext } from './PostContext';

// posts(投稿一覧)とsetPosts(投稿の追加・更新関数)を取得して使用可能にします。
const { posts, setPosts } = useContext(PostContext);

4. Profile.jsで該当ユーザーの投稿を表示

Profile.js
// Profileコンポーネントでも、Contextから投稿データを使うための準備をします。
import React, { useContext } from 'react';
import { PostContext } from './PostContext';

function Profile() {

  // 投稿データ一覧だけ取得します。更新は不要なのでsetPostsは使いません。
  const { posts } = useContext(PostContext);

  // すべての投稿から、userId(メールアドレス)に一致する投稿だけを抽出しています。
  const userPosts = posts.filter((post) => post.user === userId);


export default Profile;

UI

スクリーンショット 2025-05-07 17.19.12.png

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?