0Pricing
tRPC End-to-End Type Safe APIs · レッスン

ライブデータサブスクリプションの実装

tRPCのサブスクリプションプロシージャを作成し、サーバーから接続中のクライアントへリアルタイム更新をプッシュします。

「ライブデータサブスクリプションの実装」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはtRPC End-to-End Type Safe APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Real-time Data with Subscriptions

Welcome to the final lesson on tRPC real-time! We've learned about WebSockets, now let's build live data features.

Subscriptions in tRPC allow your server to push real-time updates to connected clients. Unlike queries (which pull data) or mutations (which modify data), subscriptions are push-based.

  • Queries: Client asks, server responds once.
  • Mutations: Client sends data, server performs action, responds once.
  • Subscriptions: Client asks once, server sends updates over time.

Defining Server Subscriptions

To create a subscription on your tRPC server, you use the createSubscription helper, similar to createQuery or createMutation.

A key difference is that a subscription procedure returns an observable. An observable is a stream of data that can emit multiple values over time.

Let's look at the basic structure.

The Observable Pattern

When defining a subscription, you'll use an observable pattern. This involves a function that receives an emit function and returns a cleanup function.

  • The emit function is what you call to send data to clients.
  • The cleanup function (returned by your subscription logic) runs when a client unsubscribes.

This allows you to manage resources like event listeners or intervals.

Server Code: Basic Live Counter

Here's a simple tRPC server-side subscription that emits a number every second. This number could represent anything, like a live user count.

import { router, publicProcedure } from './trpc';
import { observable } from '@trpc/server/observable';

export const appRouter = router({
  onUpdate: publicProcedure.subscription(() => {
    // This is where we create the observable
    return observable<number>((emit) => {
      let count = 0;
      const interval = setInterval(() => {
        count++;
        emit.next(count); // Push new data to clients
      }, 1000);

      // Return a cleanup function
      return () => {
        clearInterval(interval);
      };
    });
  }),
});

// This code is illustrative and not directly runnable
// without a full Node.js server setup.
// For context, 'router' and 'publicProcedure' would be
// initialized from '@trpc/server'.

Understanding the Server Flow

In the previous example:

  • publicProcedure.subscription(() => {...}) defines the subscription endpoint.
  • observable((emit) => {...}) creates a data stream that will send number types.
  • emit.next(count) is called repeatedly inside setInterval to push the current count to all subscribed clients.
  • The returned function () => { clearInterval(interval); } ensures the interval stops when a client disconnects or unsubscribes, preventing memory leaks.

Consuming Subscriptions on the Client

On the client-side, tRPC provides a convenient hook for consuming subscriptions, typically trpc.useSubscription if you're using React Query.

This hook works similarly to useQuery but maintains an open connection and updates your component whenever new data arrives from the server.

Client Code: React Component Example

Here's a React component that subscribes to our onUpdate procedure and displays the live counter. Notice how data updates automatically.

import React from 'react';

// Mock tRPC client for runnable example
const mockTRPCClient = {
  onUpdate: {
    subscribe: (opts) => {
      let count = 0;
      const interval = setInterval(() => {
        count++;
        opts.onData(count); // Simulate server pushing data
      }, 1000);
      return { // Return unsubscribe function
        unsubscribe: () => clearInterval(interval),
      };
    },
  },
};

// Mock useSubscription hook
const useSubscription = (path, input, { onData, onError }) => {
  React.useEffect(() => {
    const subscription = mockTRPCClient[path].subscribe({
      onData,
      onError,
    });
    return () => subscription.unsubscribe();
  }, [path, input, onData, onError]);
};

function LiveCounter() {
  const [currentCount, setCurrentCount] = React.useState(0);

  useSubscription(
    'onUpdate', // Path to your tRPC subscription
    undefined,  // No input for this subscription
    {
      onData(data) {
        setCurrentCount(data); // Update state with new data
      },
      onError(err) {
        console.error('Subscription error:', err);
      },
    }
  );

  return (
    <div>
      <h3>Live Counter:</h3>
      <p>Current value: <b>{currentCount}</b></p>
    </div>
  );
}

// This would be rendered by a framework like React.
// For runnable purposes, we can simulate a main entry point.
export default function Main() {
  return <LiveCounter />;
}

Subscriptions with Input

Just like queries and mutations, subscriptions can accept input. This is incredibly useful for filtering or customizing the data stream for each client.

For example, you might subscribe to updates for a specific productId or a particular chat roomName.

You'll define the input schema using Zod on the server and pass the input object on the client.

Code: Subscription with Input

Here's how you'd define a subscription that takes a topic string as input on the server, and how a client would use it.

/* --- SERVER-SIDE (Illustrative) --- */
import { z } from 'zod';
import { router, publicProcedure } from './trpc';
import { observable } from '@trpc/server/observable';

export const appRouterWithInput = router({
  onTopicUpdate: publicProcedure
    .input(z.object({ topic: z.string() })) // Define input schema
    .subscription(({ input }) => {
      return observable<string>((emit) => {
        // Simulate updates for a specific topic
        const interval = setInterval(() => {
          emit.next(`Update for '${input.topic}': ${Date.now()}`);
        }, 2000);
        return () => clearInterval(interval);
      });
    }),
});

/* --- CLIENT-SIDE (React Component) --- */
import React from 'react';

// Mock tRPC client for runnable example
const mockTRPCClientWithInput = {
  onTopicUpdate: {
    subscribe: (input, opts) => {
      const interval = setInterval(() => {
        opts.onData(`Update for '${input.topic}': ${Date.now()}`);
      }, 2000);
      return {
        unsubscribe: () => clearInterval(interval),
      };
    },
  },
};

// Mock useSubscription hook for runnable example
const useSubscriptionWithInput = (path, input, { onData, onError }) => {
  React.useEffect(() => {
    const subscription = mockTRPCClientWithInput[path].subscribe(
      input,
      { onData, onError }
    );
    return () => subscription.unsubscribe();
  }, [path, input, onData, onError]);
};

function TopicUpdates({ topic }) {
  const [latestUpdate, setLatestUpdate] = React.useState('');

  useSubscriptionWithInput(
    'onTopicUpdate', 
    { topic }, // Pass the input object
    {
      onData(data) {
        setLatestUpdate(data);
      },
      onError(err) {
        console.error('Subscription error:', err);
      },
    }
  );

  return (
    <div>
      <h4>Topic: {topic}</h4>
      <p>{latestUpdate}</p>
    </div>
  );
}

export default function Main() {
  return (
    <div>
      <TopicUpdates topic="news" />
      <TopicUpdates topic="sports" />
    </div>
  );
}

Best Practices for Subscriptions

When working with tRPC subscriptions, consider these best practices:

  • Cleanup: Always return a cleanup function from your observable to release resources (e.g., clear intervals, close database connections).
  • Error Handling: Implement onError callbacks on the client to gracefully handle subscription errors.
  • Rate Limiting: Be mindful of how frequently you emit data to avoid overwhelming clients or your server.
  • When to Use: Subscriptions are great for truly real-time data. For less critical updates, traditional queries with polling or client-side caching might be sufficient.
  • Authentication/Authorization: Use tRPC middleware to protect subscription procedures, ensuring only authorized users receive updates.

Quick Check: Subscription Basics

You've defined a tRPC subscription that emits a string every 5 seconds. Which part of the client-side useSubscription hook would you use to process each incoming string?

Recap: Live Data Subscriptions

In this lesson, you've learned to implement live data subscriptions with tRPC:

  • Server-side: Define subscription procedures using publicProcedure.subscription and return an observable.
  • Observable Logic: Use the emit.next() function to push data and return a cleanup function.
  • Client-side: Consume subscriptions using trpc.useSubscription, providing an onData callback to handle incoming real-time updates.
  • Input: Pass arguments to subscriptions for filtered or customized data streams.

Congratulations! You can now build powerful real-time features with tRPC's end-to-end type safety.

よくある質問

「ライブデータサブスクリプションの実装」レッスンは無料ですか?

はい。「ライブデータサブスクリプションの実装」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、tRPC End-to-End Type Safe APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。

「ライブデータサブスクリプションの実装」で何を学びますか?

tRPCのサブスクリプションプロシージャを作成し、サーバーから接続中のクライアントへリアルタイム更新をプッシュします。 ブラウザで直接実行するハンズオンコードでtRPC End-to-End Type Safe APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

tRPC End-to-End Type Safe APIsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのtRPC End-to-End Type Safe APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「ライブデータサブスクリプションの実装」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このtRPC End-to-End Type Safe APIsレッスンでコードを書いて実行できますか?

はい。すべてのtRPC End-to-End Type Safe APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. tRPCによるリアルタイム通信入門
  2. サブスクリプション用WebSocketの設定
  3. ライブデータサブスクリプションの実装
  4. 再接続とサブスクリプションのクリーンアップ
← tRPC End-to-End Type Safe APIsに戻る