-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
45 lines (37 loc) · 1.17 KB
/
App.tsx
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
import { useEffect, useRef } from "react";
import type { WorkerMessage, WorkerResponse } from "./types";
export default function App() {
const worker = useRef<Worker | null>(null);
// Send message to worker (type-safe from `WorkerMessage`)
const sendMessage = () => {
if (worker.current) {
worker.current.postMessage({
type: "feed.get",
source: "https://www.sandromaglione.com/feed",
} satisfies WorkerMessage);
}
};
useEffect(() => {
const url = new URL("./feed.ts", import.meta.url);
const newWorker = new Worker(url, { type: "module" });
// Handle all possible messages (type-safe from `WorkerResponse`)
newWorker.onmessage = (event: MessageEvent<WorkerResponse>) => {
if (event.data.type === "feed.get") {
// Received message from worker (type-safe) ✨
}
};
newWorker.onerror = (error: ErrorEvent) => {
// Handle error from worker (`ErrorEvent`)
};
worker.current = newWorker;
return () => {
// Clean up worker when component unmounts
newWorker.terminate();
};
}, []);
return (
<button type="button" onClick={sendMessage}>
Send
</button>
);
}