React hooks for real-time data streaming and subscriptions using @leancodepl/pipe
npm install @leancodepl/hook-pipe-clientReact hooks for real-time data subscriptions using @leancodepl/pipe.
``bash`
npm install @leancodepl/hook-pipe-clientor
yarn add @leancodepl/hook-pipe-client
Creates React hooks for real-time data subscriptions using @leancodepl/pipe.
Parameters:
- pipe: Pipe - Pipe instance from @leancodepl/pipe
Returns: Object containing createTopic method for creating typed hooks
Options for topic subscription hooks.
Properties:
- [NotificationType]?: (data: NotificationData) => void - Type-specific handlers for each notification typeonData?: (data: NotificationsUnion
- - Callback for all notifications
`typescript
import { mkPipeClient } from "@leancodepl/hook-pipe-client"
import { createPipe } from "@leancodepl/pipe"
const pipe = createPipe({
url: "wss://api.example.com/pipe",
getAccessToken: () => localStorage.getItem("token"),
})
const pipeClient = mkPipeClient({ pipe })
`
`typescript
import React, { useState } from 'react';
interface ChatTopic {
roomId: string;
}
interface ChatNotifications {
MessageReceived: {
id: string;
content: string;
authorId: string;
};
}
const useChatTopic = pipeClient.createTopic
function ChatRoom({ roomId }: { roomId: string }) {
const [messages, setMessages] = useState
const { data } = useChatTopic(
{ roomId },
{
MessageReceived: (data) => {
setMessages(prev => [...prev, data.content]);
},
// or
onData: (notification) => {
if (notification.type === 'MessageReceived') {
setMessages(prev => [...prev, notification.data.content]);
}
},
}
);
return (
$3
`typescript
import React, { useState } from 'react';interface MetricsTopic {
dashboardId: string;
}
interface MetricsNotifications {
CpuUpdate: { value: number };
MemoryUpdate: { value: number };
}
const useMetricsTopic = pipeClient.createTopic('metrics');
function Dashboard() {
const [cpu, setCpu] = useState(0);
const [memory, setMemory] = useState(0);
useMetricsTopic(
{ dashboardId: 'main' },
{
CpuUpdate: (data) => {
setCpu(data.value);
},
MemoryUpdate: (data) => {
setMemory(data.value);
}
// or
onData: (notification) => {
if (notification.type === 'CpuUpdate') {
setCpu(notification.data.value);
} else if (notification.type === 'MemoryUpdate') {
setMemory(notification.data.value);
}
},
}
);
return (
CPU: {cpu}%
Memory: {memory}%
);
}
``