aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/hooks/useSocket.ts
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/hooks/useSocket.ts')
-rw-r--r--app/src/hooks/useSocket.ts104
1 files changed, 104 insertions, 0 deletions
diff --git a/app/src/hooks/useSocket.ts b/app/src/hooks/useSocket.ts
new file mode 100644
index 0000000..8e2e695
--- /dev/null
+++ b/app/src/hooks/useSocket.ts
@@ -0,0 +1,104 @@
+"use client";
+
+import { useEffect, useRef, useState } from 'react';
+import { io, Socket } from 'socket.io-client';
+
+export const useSocket = () => {
+ const [isConnected, setIsConnected] = useState(false);
+ const socketRef = useRef<Socket | null>(null);
+
+ useEffect(() => {
+ // Initialize socket connection only on client
+ if (typeof window === 'undefined') return;
+
+ // Create a socket connection
+ const socket = io({
+ path: '/api/socket',
+ addTrailingSlash: false,
+ });
+
+ // Set up event handlers
+ socket.on('connect', () => {
+ console.log('Socket connected:', socket.id);
+ setIsConnected(true);
+ });
+
+ socket.on('disconnect', () => {
+ console.log('Socket disconnected');
+ setIsConnected(false);
+ });
+
+ socket.on('connect_error', (err) => {
+ console.error('Socket connection error:', err);
+ setIsConnected(false);
+ });
+
+ // Store socket reference
+ socketRef.current = socket;
+
+ // Clean up on unmount
+ return () => {
+ socket.disconnect();
+ };
+ }, []);
+
+ // Join a location share room
+ const joinLocationShare = (shareToken: string) => {
+ if (socketRef.current && shareToken) {
+ socketRef.current.emit('share:join', shareToken);
+ }
+ };
+
+ // Leave a location share room
+ const leaveLocationShare = (shareToken: string) => {
+ if (socketRef.current && shareToken) {
+ socketRef.current.emit('share:leave', shareToken);
+ }
+ };
+
+ // Send a location update
+ const sendLocationUpdate = (data: {
+ latitude: number;
+ longitude: number;
+ accuracy?: number;
+ shareToken?: string;
+ }) => {
+ if (socketRef.current) {
+ socketRef.current.emit('location:update', {
+ ...data,
+ timestamp: new Date().toISOString(),
+ });
+ }
+ };
+
+ // Subscribe to location updates for a specific share
+ const subscribeToLocationUpdates = (
+ shareToken: string,
+ callback: (data: any) => void
+ ) => {
+ if (!socketRef.current) return () => {};
+
+ // Join the location share room
+ joinLocationShare(shareToken);
+
+ // Listen for location updates
+ socketRef.current.on('location:updated', callback);
+
+ // Return cleanup function
+ return () => {
+ if (socketRef.current) {
+ socketRef.current.off('location:updated', callback);
+ leaveLocationShare(shareToken);
+ }
+ };
+ };
+
+ return {
+ socket: socketRef.current,
+ isConnected,
+ joinLocationShare,
+ leaveLocationShare,
+ sendLocationUpdate,
+ subscribeToLocationUpdates,
+ };
+}; \ No newline at end of file