مكوّنات الخادم وجلب بيانات tRPC
تعرّفوا على كيفية جلب البيانات مباشرةً في مكوّنات خادم Next.js باستخدام tRPC لتحقيق الأداء الأمثل.
مكوّنات الخادم وجلب بيانات tRPC درس مجاني في tRPC End-to-End Type Safe APIs على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في tRPC End-to-End Type Safe APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة tRPC End-to-End Type Safe APIs 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Intro to Server Components
Welcome! In Next.js, Server Components (SCs) are a powerful feature that lets you render parts of your UI directly on the server.
This means less JavaScript sent to the browser, faster initial page loads, and improved SEO!
Data Fetching on the Server
A key benefit of Server Components is their ability to fetch data directly on the server. Unlike Client Components, SCs don't need to make API calls from the browser.
This allows data to be fetched and rendered before the page is even sent to the client, boosting performance.
tRPC's Role in SCs
This is where tRPC shines! When used in Server Components, tRPC allows you to call your backend procedures directly, without any HTTP overhead.
It's like importing a local function, but with end-to-end type safety guaranteed by tRPC and TypeScript.
Build a Server-Side Caller
To fetch data in Server Components, we need a special tRPC client that calls procedures directly, bypassing HTTP. This is often called a "server-side caller" or "server client."
It uses your tRPC router directly to ensure type safety without network overhead. Here's a simplified example:
import { appRouter } from '@/server/routers/_app';
import { createCallerFactory } from '@trpc/server';
// Create a tRPC caller that can be used on the server
const createCaller = createCallerFactory(appRouter);
export const serverClient = createCaller({});
// Context can be passed here, e.g., createCaller({ user: currentUser })Fetching Data in an SC
Now, let's use our serverClient to fetch data directly within a Next.js Server Component. Notice how it looks just like calling a local function!
The data is fetched on the server before the component is rendered and sent to the client.
// app/page.tsx (Server Component)
import { serverClient } from '@/utils/trpc';
export default async function HomePage() {
const posts = await serverClient.post.list(); // Call a tRPC query
return (
<div>
<h1>Latest Posts</h1>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}SC Data to Client Components
Server Components often fetch data, but UI interactions happen in Client Components. You can pass the fetched data as props from an SC to a CC.
Remember to mark client components with "use client" at the top.
// components/PostList.tsx (Client Component)
"use client";
interface Post {
id: string;
title: string;
}
export function PostList({ posts }: { posts: Post[] }) {
// Client-side interactions can happen here
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
// app/page.tsx (Server Component, updated)
import { serverClient } from '@/utils/trpc';
import { PostList } from '@/components/PostList';
export default async function HomePage() {
const posts = await serverClient.post.list();
return (
<div>
<h1>Latest Posts</h1>
<PostList posts={posts} /> {/* Pass data as props */}
</div>
);
}Queries with Input Parameters
Just like regular tRPC queries, you can pass input parameters to your server-side tRPC calls. This is useful for fetching specific data based on URL parameters or other server-side logic.
// app/posts/[id]/page.tsx (Server Component)
import { serverClient } from '@/utils/trpc';
interface PostPageProps {
params: { id: string };
}
export default async function PostPage({ params }: PostPageProps) {
const { id } = params;
const post = await serverClient.post.byId({ id }); // Pass 'id' as input
if (!post) {
return <div>Post not found!</div>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}Graceful Error Handling
Errors thrown by your tRPC procedures on the server will propagate up to the Server Component. You can use standard JavaScript try...catch blocks to handle them.
This ensures your application remains robust even if data fetching fails.
// app/page.tsx (Server Component with error handling)
import { serverClient } from '@/utils/trpc';
export default async function HomePage() {
let posts = [];
let error = null;
try {
posts = await serverClient.post.list();
} catch (e) {
console.error("Failed to fetch posts:", e);
error = "Could not load posts. Please try again.";
}
return (
<div>
<h1>Latest Posts</h1>
{error && <p style={{ color: 'red' }}>{error}</p>}
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}SC vs. CC Data Fetching
When should you use Server Components for data fetching versus Client Components (e.g., with React Query)?
- Server Components: Ideal for initial data, SEO, static/server-rendered content, and reducing client bundle size.
- Client Components: Best for interactive data, real-time updates, user-specific data after initial load, and mutations.
Often, you'll use a mix of both!
Server Component Data Fetch
Consider a Next.js App Router project using tRPC. You need to display a list of products on the initial page load, which should be fast and SEO-friendly.
Recap: SCs & tRPC
In this lesson, we explored fetching data directly within Next.js Server Components using tRPC.
- We learned to create a server-side tRPC caller.
- Fetched data directly in Server Components.
- Passed fetched data as props to Client Components.
- Handled query parameters and errors in SCs.
- Understood the distinction between SC and CC data fetching.
This approach combines tRPC's type safety with Server Components' performance benefits for robust and efficient data fetching.
تعلم tRPC End-to-End Type Safe APIs مع معلم ذكاء اصطناعي — مجانًا
اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.
- الدورات
- 10
- الدروس
- 40
الأسئلة الشائعة
هل درس «مكوّنات الخادم وجلب بيانات tRPC» مجاني؟
نعم — نص درس «مكوّنات الخادم وجلب بيانات tRPC» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة tRPC End-to-End Type Safe APIs، انتقل إلى CoddyKit PRO. تتضمن دورة tRPC End-to-End Type Safe APIs 4 دروس في المجموع.
ماذا ستتعلم في «مكوّنات الخادم وجلب بيانات tRPC»؟
تعرّفوا على كيفية جلب البيانات مباشرةً في مكوّنات خادم Next.js باستخدام tRPC لتحقيق الأداء الأمثل. تتمرن على tRPC End-to-End Type Safe APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ tRPC End-to-End Type Safe APIs؟
لا تُشترط خبرة سابقة. tRPC End-to-End Type Safe APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «مكوّنات الخادم وجلب بيانات tRPC»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس tRPC End-to-End Type Safe APIs هذا؟
نعم. كل درس في tRPC End-to-End Type Safe APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- tRPC مع موجّه تطبيقات Next.js
- دمج React Query المتقدم
- مكوّنات الخادم وجلب بيانات tRPC
- التحديثات التفاؤلية مع طفرات tRPC