live action

This commit is contained in:
2025-11-26 19:58:46 +03:00
parent 732603559a
commit e07c5933ee
10 changed files with 349 additions and 159 deletions

View File

@@ -0,0 +1,75 @@
import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { useSocket } from "./socket-provider";
type LiveState = {
value: number;
running: boolean;
};
type LiveContextValue = LiveState & {
startCounter: () => void;
stopCounter: () => void;
};
const LiveContext = createContext<LiveContextValue | undefined>(undefined);
export const LiveProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const socket = useSocket();
const [state, setState] = useState<LiveState>({ value: 0, running: false });
useEffect(() => {
if (!socket) return;
const handleUpdate = (payload: { value: number }) => {
setState({ value: payload.value, running: true });
};
const handleStopped = (payload: { value: number }) => {
setState({ value: payload.value, running: false });
};
socket.on("counter:update", handleUpdate);
socket.on("counter:stopped", handleStopped);
socket.emit("counter:status", (payload: { value: number; running: boolean }) => {
setState({ value: payload.value, running: payload.running });
});
return () => {
socket.off("counter:update", handleUpdate);
socket.off("counter:stopped", handleStopped);
};
}, [socket]);
const startCounter = useMemo(
() => () => {
socket?.emit("counter:start");
},
[socket]
);
const stopCounter = useMemo(
() => () => {
socket?.emit("counter:stop");
},
[socket]
);
const value = useMemo(
() => ({
value: state.value,
running: state.running,
startCounter,
stopCounter
}),
[state, startCounter, stopCounter]
);
return <LiveContext.Provider value={value}>{children}</LiveContext.Provider>;
};
export function useLiveCounter() {
const ctx = useContext(LiveContext);
if (!ctx) throw new Error("useLiveCounter LiveProvider içinde kullanılmalı");
return ctx;
}