File size: 1,218 Bytes
ffb4c35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { useEffect } from 'react';
import { useSocket } from '../context/SocketContext';
import toast from 'react-hot-toast';

export const useSocketEvent = (event, handler) => {
  const { socket } = useSocket();

  useEffect(() => {
    if (socket) {
      socket.on(event, handler);
      return () => {
        socket.off(event, handler);
      };
    }
  }, [socket, event, handler]);
};

export const useTaskNotifications = () => {
  const { socket } = useSocket();

  useEffect(() => {
    if (socket) {
      const handleTaskUpdate = (data) => {
        toast.success(`Task "${data.title}" has been updated`);
      };

      const handleNewTask = (data) => {
        toast.success(`New task "${data.title}" assigned to you`);
      };

      const handleTaskComment = (data) => {
        toast(`${data.user} commented on "${data.taskTitle}"`);
      };

      socket.on('task:update', handleTaskUpdate);
      socket.on('task:new', handleNewTask);
      socket.on('task:comment', handleTaskComment);

      return () => {
        socket.off('task:update', handleTaskUpdate);
        socket.off('task:new', handleNewTask);
        socket.off('task:comment', handleTaskComment);
      };
    }
  }, [socket]);
};