Claude Code के साथ Build a Notification System कैसे करें
Claude Code का उपयोग करके build a notification system सीखें। Practical code examples और step-by-step guidance शामिल है।
通知システムのbuildको Claude Code से Efficient बनाएं
Webアプリにおける通知は、トーストdisplay सेプッシュ通知、リアルタイムupdate तक多岐にわたり है।Claude Code का उपयोग करके、これらをintegrationした通知基盤をकम समय मेंbuild किया जा सकता है。
トースト通知componentのimplementation
まずはアプリ内でuse करनाトースト通知を作り है।
> libraryを使わずにトースト通知componentをReactで作って。
> success/error/warning/infoの4種類。自動で消える。スタックdisplaysupport。
import { createContext, useContext, useState, useCallback, type ReactNode } from "react";
type ToastType = "success" | "error" | "warning" | "info";
interface Toast {
id: string;
type: ToastType;
message: string;
}
interface ToastContextType {
addToast: (type: ToastType, message: string) => void;
}
const ToastContext = createContext<ToastContextType | null>(null);
const TOAST_STYLES: Record<ToastType, string> = {
success: "bg-green-500 text-white",
error: "bg-red-500 text-white",
warning: "bg-yellow-500 text-black",
info: "bg-blue-500 text-white",
};
const TOAST_ICONS: Record<ToastType, string> = {
success: "✓",
error: "✕",
warning: "⚠",
info: "ℹ",
};
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const addToast = useCallback((type: ToastType, message: string) => {
const id = crypto.randomUUID();
setToasts((prev) => [...prev, { id, type, message }]);
setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, 4000);
}, []);
return (
<ToastContext.Provider value={{ addToast }}>
{children}
<div className="fixed bottom-4 right-4 flex flex-col gap-2 z-50">
{toasts.map((toast) => (
<div
key={toast.id}
className={`px-4 py-3 rounded-lg shadow-lg flex items-center gap-2 animate-slide-in ${TOAST_STYLES[toast.type]}`}
>
<span>{TOAST_ICONS[toast.type]}</span>
<span>{toast.message}</span>
<button
onClick={() => setToasts((prev) => prev.filter((t) => t.id !== toast.id))}
className="ml-2 opacity-70 hover:opacity-100"
>
✕
</button>
</div>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast() {
const context = useContext(ToastContext);
if (!context) throw new Error("useToast must be used within ToastProvider");
return context;
}
WebSocketによるリアルタイム通知
server सेのリアルタイム通知を受け取る仕組みもbuild किया जा सकता है。
// Server side(Node.js + ws)
import { WebSocketServer, WebSocket } from "ws";
interface Client {
ws: WebSocket;
userId: string;
}
const clients: Client[] = [];
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws, req) => {
const userId = new URL(req.url!, `http://${req.headers.host}`).searchParams.get("userId");
if (!userId) return ws.close();
clients.push({ ws, userId });
ws.on("close", () => {
const index = clients.findIndex((c) => c.ws === ws);
if (index !== -1) clients.splice(index, 1);
});
});
// 特定userへの通知送信
export function sendNotification(userId: string, notification: object) {
clients
.filter((c) => c.userId === userId)
.forEach((c) => c.ws.send(JSON.stringify(notification)));
}
// Client sideのhook
import { useEffect, useRef, useCallback } from "react";
interface Notification {
id: string;
type: string;
title: string;
body: string;
}
export function useNotifications(userId: string, onNotification: (n: Notification) => void) {
const wsRef = useRef<WebSocket | null>(null);
const connect = useCallback(() => {
const ws = new WebSocket(`ws://localhost:8080?userId=${userId}`);
ws.onmessage = (event) => {
const notification = JSON.parse(event.data);
onNotification(notification);
};
ws.onclose = () => {
setTimeout(connect, 3000); // Reconnect
};
wsRef.current = ws;
}, [userId, onNotification]);
useEffect(() => {
connect();
return () => wsRef.current?.close();
}, [connect]);
}
通知の永続化と既読management
通知をDBに保存して既読managementするfeaturesもaddでき है।
// Prismaスkeyマ से自動でAPIgenerateを依頼
// schema.prisma の内容をClaude Codeが読み取ってimplementation
import { db } from "@/lib/database";
export async function getNotifications(userId: string) {
return db.notification.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
take: 50,
});
}
export async function markAsRead(notificationId: string) {
return db.notification.update({
where: { id: notificationId },
data: { readAt: new Date() },
});
}
export async function getUnreadCount(userId: string) {
return db.notification.count({
where: { userId, readAt: null },
});
}
Claude Code सेのdevelopment効率をऊपरげるには生産性を3倍にする10のTipsをreference के लिए देखें。formとのintegrationके बारे मेंはformvalidation設計も併せてदेखें。
Summary
Claude Code का उपयोग करके、トースト通知、リアルタイム通知、永続化 तक शामिल通知システム全体をefficientlybuild किया जा सकता है。自然言語で要件を伝え、段階的にfeaturesをadd करोいくのがおすすめ है।
official documentationはClaude Code सेconfirmでき है।
Related Posts
Claude Code Hooks में Mastery: Auto-Format, Auto-Test, और बहुत कुछ
Claude Code hooks से auto-formatting और auto-testing setup करना सीखें। Practical configuration examples और real-world use cases शामिल हैं।
Claude Code MCP Server Setup और Practical Use Cases
Claude Code की MCP server capabilities की comprehensive guide। External tools connect करना, servers configure करना, और real-world integration examples सीखें।
CLAUDE.md लिखने की Complete Guide: Project Configuration की Best Practices
Effective CLAUDE.md files लिखने की thorough guide। अपना tech stack, conventions, और project structure communicate करना सीखें और Claude Code की output quality maximize करें।