-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventContext.js
43 lines (35 loc) · 1.16 KB
/
EventContext.js
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
// EventContext.js
import React, { createContext, useContext, useState } from 'react';
const EventContext = createContext();
export const EventProvider = ({ children }) => {
const [subscriptions, setSubscriptions] = useState({});
const subscribe = (eventName, handler) => {
setSubscriptions((prevSubscriptions) => ({
...prevSubscriptions,
[eventName]: [...(prevSubscriptions[eventName] || []), handler],
}));
};
const publish = (eventName, data) => {
const eventSubscriptions = subscriptions[eventName] || [];
eventSubscriptions.forEach((handler) => handler(data));
};
return (
<EventContext.Provider value={{ subscribe, publish }}>
{children}
</EventContext.Provider>
);
};
export const useEvent = (eventName, handler) => {
const { subscribe, publish } = useContext(EventContext);
subscribe(eventName, handler);
return () => {
const eventSubscriptions = subscriptions[eventName] || [];
const updatedSubscriptions = eventSubscriptions.filter(
(sub) => sub !== handler
);
setSubscriptions((prevSubscriptions) => ({
...prevSubscriptions,
[eventName]: updatedSubscriptions,
}));
};
};