مشروع Social: AuthContext و useAuth

المستخدم الحالي بقى جاي من السيرفر: AuthProvider بيجيبه من /users/profile-data أول ما التطبيق يفتح، ويحطه في AuthContext، و useAuth بيقراه في أي مكوّن. الـ context والـ hook في ملف، والـ Provider في ملف، زي مشروع Social. وتحدي: صفحة البروفايل بـ useAuth.

01 / ملخص الدرس

مشروع Social: AuthContext و useAuth

المستخدم الحالي بقى جاي من السيرفر: AuthProvider بيجيبه من /users/profile-data أول ما التطبيق يفتح، ويحطه في AuthContext، و useAuth بيقراه في أي مكوّن. الـ context والـ hook في ملف، والـ Provider في ملف، زي مشروع Social. وتحدي: صفحة البروفايل بـ useAuth.

02 / شرح الدرس مكتوبًا

نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.

أهلًا بيك. من أول المشروع، المستخدم الحالي جاي من ملف data.js، مكتوب بإيدينا. النهارده هييجي من الـ server، وهيتحط في Context، وكل component هياخده من هناك. ده أول خطوة حقيقية في تسجيل الدخول. الـ server عنده endpoint اسمه slash users slash profile-data: بيرجّع بيانات المستخدم صاحب الـ token. نضيف authService فيه me. ملف جديد في folder context: AuthContext.js. فيه الـ context نفسه، و useAuth بالحماية، زي اللي عملناه في الدرس اللي فات بالزبط. وليه ملف لوحده؟ لأن Vite بيحب ملف الـ component يصدّر components بس، علشان الـ Hot Reload يشتغل صح. فالـ context والـ hook في ملف، والـ component Provider في ملف تاني. ومشروع Social مقسمهم كده بالزبط. و AuthProvider.jsx. state للمستخدم، و state للتحميل. و effect بيجيب me أول ما التطبيق يفتح. المرة دي كتبناه بـ then و catch و finally بدل async و await، الاتنين بيعملوا نفس الحاجة، ومشروع Social بيستخدم الشكل ده هنا. ولحد ما الرد ييجي، بنعرض: بنجهّز حسابك. وبعدها الـ Provider، والـ value فيه user و setUser.

و App: نلف الـ RouterProvider بالـ AuthProvider. كده كل الصفحات تحته، وكلها تقدر تقرا المستخدم. بنجهّز حسابك لحزة، وبعدين التطبيق. والـ console فيه request profile-data. بس الـ components لسه بتقرا من data.js. نبدل في الـ components. في Nav و Layout: بدل import currentUser، import useAuth. وأول سطر في الـ component: user من useAuth. وكل currentUser بقت user. وفي Layout حاجة صغيرة: الاقتراحات كانت بتعمل map بمتغير اسمه user، وده هيتلخبط مع user بتاعنا، فسميناه u. ونفس الكلام في الـ Feed والـ Composer والـ card. الترحيب، وصورة الـ Composer، و liked و own في الـ card، كلهم بقوا من useAuth. كل حاجة شغالة، والمستخدم جاي من الـ server. وأرقام المتابعين في الـ list بقت أرقام حقيقية من الـ server.

التحدي، والمطلوب بالزبط: صفحة الـ profile لسه بتعمل import لـ currentUser. اعمل import لـ useAuth بدلها. وفي أول الـ component، خد user من useAuth، بس سميه me، لأن الصفحة فيها متغير اسمه user تحت، بيانات صاحب الـ profile. في destructuring، تكتب user colon me، زي ما عملنا مع post colon initial. و target يبقى userId أو me dot underscore id. دورك.

تمرين

Profile: const { user: me } = useAuth(); و target = userId ?? me._id

الحل: الـ import، و me من useAuth، و target. ودلوقتي data.js ملوش أي لازمة، ومحدش بيعمله import، فتقدر تمسحه من مشروعك، ومن الدرس الجاي مش هتلاقيه هنا. ندوس صورتي. الـ profile بتاعي شغال، والـ id جاي من الـ context. بس لحد دلوقتي الـ server التجريبي بيعتبرنا محمود من غير ما نسجل دخول. الدرس الجاي: صفحة تسجيل الدخول، والـ server هيطلب الـ token بجد.

services/social.js
import { mediaForm, request } from "./api";

// كل طلبات التطبيق بأسامي مفهومة. القوايم بترجع { items, pagination } علشان useCollection.
const collection = (result, items) => ({ items, pagination: result.meta?.pagination });

const feedPaths = {
  all: "/posts?",
  following: "/posts/feed?only=following&",
  images: "/posts/feed?only=all&hasImage=true&",
};

export const authService = {
  me: (signal) => request("/users/profile-data", { signal }),
};

export const postService = {
  list: async (page = 1, signal, tab = "all") => {
    if (tab === "saved") {
      const result = await request(`/users/bookmarks?page=${page}&limit=10`, { signal });
      return collection(result, result.data.bookmarks);
    }
    const result = await request(`${feedPaths[tab]}page=${page}&limit=10`, { signal });
    return collection(result, result.data.posts);
  },
  userPosts: async (userId, page = 1, signal) => {
    const result = await request(`/users/${userId}/posts?page=${page}&limit=10`, { signal });
    return collection(result, result.data.posts);
  },
  one: (postId, signal) => request(`/posts/${postId}`, { signal }),
  create: (text, image) => request("/posts", { method: "POST", body: mediaForm("body", text, image) }),
  remove: (postId) => request(`/posts/${postId}`, { method: "DELETE" }),
  like: (postId) => request(`/posts/${postId}/like`, { method: "PUT" }),
  bookmark: (postId) => request(`/posts/${postId}/bookmark`, { method: "PUT" }),
};

export const userService = {
  profile: (userId, signal) => request(`/users/${userId}/profile`, { signal }),
  suggestions: async (page = 1, signal, limit = 4) => {
    const result = await request(`/users/suggestions?page=${page}&limit=${limit}`, { signal });
    return collection(result, result.data.suggestions);
  },
};

export const notificationService = {
  count: (signal) => request("/notifications/unread-count", { signal }),
};
pages/Feed.jsx
import { useCallback } from "react";
import { useSearchParams } from "react-router";
import useCollection from "../hooks/useCollection";
import PostCard from "../components/PostCard";
import Composer from "../components/Composer";
import { EmptyState, ErrorState, PaginationControls, Skeleton } from "../components/Status";
import { useAuth } from "../context/AuthContext";
import { postService } from "../services/social";

const tabs = [
  { id: "all", label: "لك" },
  { id: "following", label: "بتتابعهم" },
  { id: "images", label: "صور بس" },
  { id: "saved", label: "المحفوظات" },
];

const empty = {
  all: ["لسه مفيش حكايات هنا", "ابدأ إنتَ بأول منشور."],
  following: ["دايرتك لسه بتكبر", "تابع ناس جديدة علشان تشوف منشوراتهم هنا."],
  images: ["مفيش صور لسه", "أول صورة تتنشر هتظهر هنا."],
  saved: ["لسه مجموعتك فاضية", "دوس علامة الحفظ على أي منشور علشان ترجع له بسهولة."],
};

const Feed = () => {
  const { user } = useAuth();
  const [params, setParams] = useSearchParams();
  const tab = params.get("tab") ?? "all";
  const loader = useCallback((page, signal) => postService.list(page, signal, tab), [tab]);
  const list = useCollection(loader);

  const changeTab = (id) => {
    setParams({ tab: id });
    list.setPage(1);
  };

  const handleCreated = (post) => {
    list.setItems((prev) => [post, ...prev]);
  };

  const handleDelete = (id) => {
    list.setItems((prev) => prev.filter((post) => post._id !== id));
  };

  return (
    <>
      <header className="mb-5">
        <span className="text-xs font-bold text-[#1877f2]">يوم جديد، حكاية جديدة</span>
        <h1 className="text-2xl font-extrabold mt-1">أهلًا، {user.name.split(" ")[0]}</h1>
        <p className="text-sm text-slate-500 mt-1">شوف جديد دايرتك، وشاركهم لحظة من يومك.</p>
      </header>
      <Composer onCreated={handleCreated} />
      <div className="flex gap-2 mb-4">
        {tabs.map((t) => (
          <button
            key={t.id}
            id={"tab-" + t.id}
            onClick={() => changeTab(t.id)}
            className={`px-4 py-1.5 rounded-full text-sm font-bold ${tab === t.id ? "bg-[#00298d] text-white" : "bg-white text-slate-600 border border-slate-200"}`}
          >
            {t.label}
          </button>
        ))}
      </div>
      {list.loading ? (
        <Skeleton />
      ) : list.error ? (
        <ErrorState message={list.error} retry={list.refresh} />
      ) : list.items.length === 0 ? (
        <EmptyState title={empty[tab][0]} text={empty[tab][1]} />
      ) : (
        <div className="space-y-4">
          {list.items.map((post) => (
            <PostCard key={post._id} post={post} onDeleted={handleDelete} />
          ))}
          <PaginationControls pagination={list.pagination} page={list.page} setPage={list.setPage} />
        </div>
      )}
    </>
  );
};

export default Feed;
pages/Profile.jsx
import { useCallback } from "react";
import { useParams } from "react-router";
import Avatar from "../components/Avatar";
import PostCard from "../components/PostCard";
import { EmptyState, ErrorState, PaginationControls, Skeleton } from "../components/Status";
import useCollection from "../hooks/useCollection";
import useResource from "../hooks/useResource";
import { useAuth } from "../context/AuthContext";
import { postService, userService } from "../services/social";

const Profile = () => {
  const { user: me } = useAuth();
  const { userId } = useParams();
  const target = userId ?? me._id;

  const userLoader = useCallback(async (signal) => {
    const result = await userService.profile(target, signal);
    return result.data.user;
  }, [target]);
  const profile = useResource(userLoader);

  const postsLoader = useCallback((page, signal) => postService.userPosts(target, page, signal), [target]);
  const list = useCollection(postsLoader);

  const handleDelete = (id) => {
    list.setItems((prev) => prev.filter((post) => post._id !== id));
  };

  if (profile.loading) return <Skeleton />;
  if (profile.error) return <ErrorState message={profile.error} retry={profile.refresh} />;
  const user = profile.data;

  return (
    <>
      <section className="bg-white rounded-2xl border border-slate-200 overflow-hidden mb-5">
        <div className="h-28 bg-gradient-to-l from-[#00298d] to-[#1877f2]" />
        <div className="px-5 pb-5 -mt-10">
          <div className="ring-4 ring-white rounded-full w-fit">
            <Avatar user={user} size="lg" />
          </div>
          <h1 className="text-xl font-extrabold mt-3">{user.name}</h1>
          <p className="text-sm text-slate-400 text-right" dir="ltr">@{user.username}</p>
          <div className="flex gap-6 mt-4 text-sm">
            <span><strong>{list.pagination?.total ?? 0}</strong> منشور</span>
            <span><strong>{user.followersCount}</strong> متابع</span>
            <span><strong>{user.followingCount}</strong> بيتابعهم</span>
          </div>
        </div>
      </section>
      {list.loading ? (
        <Skeleton />
      ) : list.error ? (
        <ErrorState message={list.error} retry={list.refresh} />
      ) : list.items.length === 0 ? (
        <EmptyState title="لسه مفيش منشورات" text="أول ما ينشر حاجة، هتظهر هنا." />
      ) : (
        <div className="space-y-4">
          {list.items.map((post) => (
            <PostCard key={post._id} post={post} onDeleted={handleDelete} />
          ))}
          <PaginationControls pagination={list.pagination} page={list.page} setPage={list.setPage} />
        </div>
      )}
    </>
  );
};

export default Profile;
App.jsx
import { createMemoryRouter, Navigate, RouterProvider } from "react-router";
import AuthProvider from "./context/AuthProvider";
import Layout from "./components/Layout";
import Feed from "./pages/Feed";
import PostDetails from "./pages/PostDetails";
import Profile from "./pages/Profile";
import Discover from "./pages/Discover";
import Soon from "./pages/Soon";
import NotFound from "./pages/NotFound";
import RouteError from "./pages/RouteError";

// في مشروعك على الجهاز: createBrowserRouter. هنا createMemoryRouter لأن الـ preview مالوش شريط عنوان.
const router = createMemoryRouter([
  {
    element: <Layout />,
    children: [
      {
        errorElement: <RouteError />,
        children: [
          { path: "/", element: <Feed /> },
          { path: "/posts/:postId", element: <PostDetails /> },
          { path: "/profile", element: <Profile /> },
          { path: "/users/:userId", element: <Profile /> },
          { path: "/discover", element: <Discover /> },
          { path: "/bookmarks", element: <Navigate to="/?tab=saved" replace /> },
          { path: "/notifications", element: <Soon title="الإشعارات" /> },
          { path: "/settings", element: <Soon title="الإعدادات" /> },
          { path: "*", element: <NotFound /> },
        ],
      },
    ],
  },
]);

export default function App() {
  return (
    <AuthProvider>
      <RouterProvider router={router} />
    </AuthProvider>
  );
}
components/Composer.jsx
import { useEffect, useState } from "react";
import Avatar from "./Avatar";
import Icon from "./Icon";
import { useAuth } from "../context/AuthContext";
import { postService } from "../services/social";
import { errorMessage } from "../services/api";

const Composer = ({ onCreated }) => {
  const { user } = useAuth();
  const [text, setText] = useState(() => localStorage.getItem("social-draft") ?? "");
  const [image, setImage] = useState(null);
  const [preview, setPreview] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const tooLong = text.length > 500;

  useEffect(() => {
    if (text) localStorage.setItem("social-draft", text);
    else localStorage.removeItem("social-draft");
  }, [text]);

  const handleFile = (file) => {
    if (!file) return;
    if (!file.type.startsWith("image/")) {
      setError("اختار صورة، مش أي ملف.");
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      setError("حجم الصورة لازم يكون أقل من 5 ميجا.");
      return;
    }
    setError("");
    setImage(file);
    setPreview(URL.createObjectURL(file));
  };

  const removeImage = () => {
    URL.revokeObjectURL(preview);
    setImage(null);
    setPreview("");
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const body = text.trim();
    if ((!body && !image) || tooLong || busy) return;
    setBusy(true);
    setError("");
    try {
      const result = await postService.create(body, image);
      onCreated(result.data.post);
      setText("");
      if (preview) URL.revokeObjectURL(preview);
      setImage(null);
      setPreview("");
    } catch (err) {
      setError(errorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-2xl border border-slate-200 p-4 mb-5">
      <div className="flex items-center gap-3 mb-3">
        <Avatar user={user} />
        <div>
          <h2 className="font-bold text-sm">شارك لحظة من يومك</h2>
          <p className="text-xs text-slate-400">فيه دايمًا حد مهتم يسمع حكايتك.</p>
        </div>
      </div>
      <textarea
        id="composer"
        value={text}
        onChange={(e) => setText(e.target.value)}
        rows={3}
        placeholder="بتفكر في إيه؟"
        className="w-full resize-none bg-slate-50 rounded-xl p-3 outline-none focus:ring-2 focus:ring-blue-200"
      />
      {preview && (
        <div className="relative mt-3">
          <img src={preview} alt="معاينة الصورة" className="w-full rounded-xl" />
          <button
            id="remove-image"
            type="button"
            onClick={removeImage}
            className="absolute top-2 left-2 size-8 grid place-items-center rounded-full bg-white/90"
            aria-label="إزالة الصورة"
          >
            <Icon name="close" />
          </button>
          <p className="text-xs text-slate-500 mt-1">{image.name} · {Math.round(image.size / 1024)} KB</p>
        </div>
      )}
  
…
components/PostCard.jsx
import { useState } from "react";
import { Link } from "react-router";
import Avatar from "./Avatar";
import Icon from "./Icon";
import { useAuth } from "../context/AuthContext";
import { formatTime } from "../services/format";
import { postService } from "../services/social";
import { errorMessage } from "../services/api";

const PostCard = ({ post: initial, onDeleted }) => {
  const { user } = useAuth();
  const [post, setPost] = useState(initial);
  const liked = post.likes.includes(user._id);
  const own = post.user._id === user._id;
  const [confirming, setConfirming] = useState(false);
  const [busy, setBusy] = useState(false);
  const [deleted, setDeleted] = useState(false);

  const handleLike = async () => {
    const previousLikes = post.likes;
    setBusy(true);
    setPost((prev) => ({
      ...prev,
      likes: liked ? prev.likes.filter((id) => id !== user._id) : [...prev.likes, user._id],
    }));
    try {
      const result = await postService.like(post._id);
      setPost((prev) => ({ ...prev, likes: result.data.post.likes }));
    } catch (e) {
      setPost((prev) => ({ ...prev, likes: previousLikes }));
      console.error(errorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async () => {
    if (!confirming) {
      setConfirming(true);
      return;
    }
    setDeleted(true);
    try {
      await postService.remove(post._id);
      onDeleted(post._id);
    } catch (e) {
      setDeleted(false);
      setConfirming(false);
      console.error(errorMessage(e));
    }
  };

  const handleSave = async () => {
    const previous = post.bookmarked;
    setBusy(true);
    setPost((prev) => ({ ...prev, bookmarked: !previous }));
    try {
      const result = await postService.bookmark(post._id);
      setPost((prev) => ({ ...prev, bookmarked: result.data.bookmarked }));
    } catch (e) {
      setPost((prev) => ({ ...prev, bookmarked: previous }));
      console.error(errorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  if (deleted) return null;

  return (
    <article className="bg-white rounded-2xl border border-slate-200 p-4">
      <header className="flex items-center gap-3">
        <Link to={own ? "/profile" : "/users/" + post.user._id}>
          <Avatar user={post.user} />
        </Link>
        <div className="flex-1 min-w-0">
          <Link id={"author-" + post._id} to={own ? "/profile" : "/users/" + post.user._id} className="block font-bold text-sm truncate hover:underline">
            {post.user.name}
          </Link>
          <Link id={"open-" + post._id} to={"/posts/" + post._id} className="text-xs text-slate-400 hover:underline">
            {formatTime(post.createdAt)}
          </Link>
        </div>
        <button
          id={"save-" + post._id}
          onClick={handleSave}
          disabled={busy}
          className={`size-9 grid place-items-center rounded-full hover:bg-slate-100 ${post.bookmarked ? "text-[#00298d] bg-blue-50" : "text-slate-50
…
03 / دروس الكورس (87)
  1. 01أهلًا بيك: هنبني إيه في الكورس ده
  2. 02React بتشتغل إزاي من جوه؟
  3. 03Vite: مشروع React حقيقي على جهازك
  4. 04قواعد JSX واحدة واحدة
  5. 05الأقواس المعووجة: JavaScript جوه JSX
  6. 06المكونات: قطع الليجو بتاعة React
  7. 07كل مكوّن في ملفه: import و export
  8. 08مشروع Social: أول قطع في التطبيق
  9. 09مشروع Social: كارت المنشور وصفحة الـ Feed
  10. 10الـ props: إزاي نبعت بيانات للمكوّن
  11. 11Destructuring وقيم افتراضية وبعت object كامل
  12. 12children: مكونات زي الإطار
  13. 13القوائم: map و key
  14. 14العرض بشرط: && و ternary و return بدري
  15. 15مشروع Social: الـ Avatar بالـ props
  16. 16مشروع Social: الـ Feed بيعرض المنشورات
  17. 17Tailwind CSS: التنسيق جوه الـ className
  18. 18Tailwind: الترتيب بـ flex و grid
  19. 19Tailwind: الموبايل والكمبيوتر، و hover و focus و disabled
  20. 20مشروع Social: كل الشكل بـ Tailwind
  21. 21مشروع Social: التخطيط بالتلات أعمدة
  22. 22الأحداث: لما المستخدم يدوس أو يكتب
  23. 23useState: ذاكرة المكوّن
  24. 24الـ state صورة ثابتة، والـ updater function
  25. 25الـ state لما يبقى object: ما تعدّلش، اعمل نسخة
  26. 26الـ arrays في الـ state: إضافة ومسح وتعديل
  27. 27مشروع Social: الإعجاب والحفظ بيشتغلوا
  28. 28مشروع Social: رفع الـ state لفوق ومسح المنشور
  29. 29مشروع Social: الـ state المحسوب وتابات الفلترة
  30. 30الـ Controlled Input: الـ state بيتحكم في الخانة
  31. 31الفورم و onSubmit: نبعت تعليق
  32. 32مشروع Social: الـ Composer ومنشور جديد
  33. 33كل أنواع الخانات في state واحد
  34. 34مشروع Social: صورة مع المنشور ومعاينتها
  35. 35useEffect: حاجة تحصل بعد ما React ترسم
  36. 36مشروع Social: المسودة بتتحفظ في المتصفح
  37. 37الـ cleanup: نقفل اللي فتحناه
  38. 38fetch: أول كلام مع السيرفر
  39. 39مشروع Social: المنشورات جاية من السيرفر
  40. 40مشروع Social: التحميل والخطأ والقايمة الفاضية
  41. 41مشروع Social: الـ race condition و AbortController
  42. 42مشروع Social: custom hook اسمه useCollection، و useCallback
  43. 43مشروع Social: الصفحات
  44. 44طبقة الخدمات: function واحدة للكلام مع السيرفر
  45. 45طبقة الخدمات: postService و userService
  46. 46مشروع Social: الإعجاب بيروح للسيرفر، و Optimistic UI
  47. 47مشروع Social: JSON و FormData، منشور جديد بيروح للسيرفر
  48. 48React Router: صفحات من غير ما الصفحة تتحمّل
  49. 49Outlet والـ routes المتداخلة و NavLink
  50. 50مشروع Social: الصفحات بـ React Router
  51. 51مشروع Social: صفحة المنشور و useParams
  52. 52مشروع Social: صفحة البروفايل
  53. 53مشروع Social: useSearchParams، الفلتر في العنوان
  54. 54مشروع Social: useNavigate و Navigate وصفحة الخطأ
  55. 55Context: بيانات يوصلها أي مكوّن من غير props
  56. 56مشروع Social: AuthContext و useAuthانت هنا
  57. 57مشروع Social: تسجيل الدخول والتوكن
  58. 58مشروع Social: الجلسة بتفضل، والرجوع للصفحة المطلوبة
  59. 59مشروع Social: تسجيل الخروج وانتهاء الجلسة
  60. 60Zod: نوصف شكل البيانات الصح مرة واحدة
  61. 61Zod: schema إنشاء الحساب كاملة و refine
  62. 62react-hook-form: فورم من غير state لكل خانة
  63. 63مشروع Social: صفحة الدخول بـ react-hook-form و Zod
  64. 64مشروع Social: صفحة إنشاء الحساب
  65. 65react-hot-toast: رسايل صغيرة بتظهر وتختفي
  66. 66مشروع Social: رسايل النجاح والخطأ
  67. 67TanStack Query: ليه، وأول useQuery
  68. 68TanStack Query: الـ Feed و queryKey اللي بيتغير
  69. 69TanStack Query: staleTime والبيانات القديمة
  70. 70TanStack Query: صفحة المنشور والبروفايل وتصميم المفاتيح
  71. 71TanStack Query: useMutation للتغيير
  72. 72TanStack Query: إعجاب متفائل جوه المخزن
  73. 73TanStack Query: حمّل المزيد بـ useInfiniteQuery
  74. 74useRef: صندوق بيفضل موجود من غير ما يرسم
  75. 75مشروع Social: التحميل وإنتَ نازل، و ref كـ prop
  76. 76مشروع Social: نافذة تعديل المنشور بـ dialog
  77. 77useReducer: كل تغييرات الـ state في مكان واحد
  78. 78مشروع Social: التعليقات
  79. 79الأداء: memo و useMemo و useCallback
  80. 80TypeScript مع React: أول خطوة
  81. 81TypeScript: أنواع بيانات السيرفر و generics
  82. 82TypeScript: الـ Context والـ hooks، ونقل المشروع
  83. 83المشروع النهائي: صفحة الإشعارات
  84. 84المشروع النهائي: المتابعة
  85. 85المشروع النهائي: الإعدادات وتغيير كلمة السر
  86. 86المشروع النهائي: البناء والنشر على الإنترنت
  87. 87الخلاصة، وإيه الخطوة الجاية