3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsとSupabaseでリアルタイムアプリを簡単に作ってみよう

Posted at

目標

  • Next.jsでリアルタイム機能の必要性を理解する。
  • Supabaseのリアルタイム機能を使ってデータを即時更新する。
  • ブログに新しい投稿が追加された際の通知を実装する。

1. リアルタイム機能の重要性

企業向けやユーザーエンゲージメントを重視するアプリでは、リアルタイム更新が求められます。Supabaseのリアルタイム機能を使えば、データベースの変更を即座にクライアントに反映できます。この記事では、ブログに新着投稿通知を追加します。


2. Supabaseリアルタイムの準備

Supabaseはリアルタイム購読をサポートしています。既存のプロジェクトで有効化します。

手順:

  1. リアルタイムの有効化
    • Supabaseダッシュボードの「Database > Tables」でpostsテーブルの「Realtime」をオン。
  2. 依存関係の確認
    • 既に@supabase/supabase-jsがインストール済み(未インストールならnpm install @supabase/supabase-js)。

3. リアルタイム購読の実装

新着投稿をリアルタイムで検知する仕組みを構築します。

lib/supabase.tsの編集:

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.SUPABASE_URL || '';
const supabaseKey = process.env.SUPABASE_KEY || '';
export const supabase = createClient(supabaseUrl, supabaseKey);

app/page.tsxの編集:

'use client';

import { useEffect, useState } from 'react';
import { supabase } from '../lib/supabase';

export default function Home() {
  const [posts, setPosts] = useState<any[]>([]);
  const [notification, setNotification] = useState<string | null>(null);

  useEffect(() => {
    // 初期データの取得
    const fetchPosts = async () => {
      const { data } = await supabase
        .from('posts')
        .select('*')
        .order('created_at', { ascending: false });
      setPosts(data || []);
    };
    fetchPosts();

    // リアルタイム購読
    const subscription = supabase
      .channel('posts-channel')
      .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'posts' }, (payload) => {
        setPosts((prev) => [payload.new, ...prev]);
        setNotification(`新着投稿: ${payload.new.title}`);
        setTimeout(() => setNotification(null), 3000); // 3秒後に通知を消す
      })
      .subscribe();

    // クリーンアップ
    return () => {
      supabase.removeChannel(subscription);
    };
  }, []);

  return (
    <div className="min-h-screen flex flex-col items-center bg-gray-100 py-8">
      <h1 className="text-4xl font-bold text-blue-600 mb-8">リアルタイム投稿</h1>
      {notification && (
        <div className="bg-green-500 text-white p-2 rounded mb-4">{notification}</div>
      )}
      <ul className="space-y-4 max-w-2xl w-full">
        {posts.map((post) => (
          <li key={post.id} className="bg-white p-4 rounded shadow">
            <a href={`/posts/${post.id}`} className="text-xl font-semibold text-blue-500 hover:underline">
              {post.title}
            </a>
            <p className="text-gray-600">{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

実践:リアルタイムブログ

  • 投稿リスト:新着投稿がリアルタイムで追加。
  • 通知:新投稿時にポップアップ通知を表示。

確認

  1. npm run devで起動。
  2. Supabaseダッシュボードからpostsテーブルに手動で投稿を追加。
  3. http://localhost:3000で通知とリスト更新を確認。

まとめ

  • Supabaseのリアルタイム機能でブログを動的に更新しました。
  • ユーザー体験を向上させる新着通知を実装しました。

この記事が役に立ったと思ったら、ぜひ「いいね」を押して、ストックしていただければ嬉しいです!リアルタイム機能をあなたのプロジェクトにもぜひ試してみてください!

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?