|
| 1 | +import { useEffect, useRef, useState } from "react"; |
| 2 | + |
| 3 | +const usePoll = (url) => { |
| 4 | + const [messages, setMessages] = useState([]); |
| 5 | + const cursorRef = useRef(0); |
| 6 | + const activeRef = useRef(true); |
| 7 | + |
| 8 | + useEffect(() => { |
| 9 | + const poll = async () => { |
| 10 | + while (activeRef.current) { |
| 11 | + try { |
| 12 | + const res = await fetch(`${url}/poll?since=${cursorRef.current}`); |
| 13 | + const data = await res.json(); |
| 14 | + |
| 15 | + if (data.messages.length > 0) { |
| 16 | + cursorRef.current = data.cursor; |
| 17 | + setMessages((prev) => [...prev, ...data.messages]); |
| 18 | + } |
| 19 | + } catch { |
| 20 | + await new Promise((r) => setTimeout(r, 2000)); |
| 21 | + } |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + poll(); |
| 26 | + return () => { |
| 27 | + activeRef.current = false; |
| 28 | + }; |
| 29 | + }, [url]); |
| 30 | + |
| 31 | + const sendMessage = async (text) => { |
| 32 | + const message = { text, time: new Date().toISOString() }; |
| 33 | + setMessages((prev) => [...prev, { ...message }]); |
| 34 | + |
| 35 | + await fetch(`${url}/message`, { |
| 36 | + method: "POST", |
| 37 | + headers: { "Content-Type": "application/json" }, |
| 38 | + body: JSON.stringify(message), |
| 39 | + }); |
| 40 | + }; |
| 41 | + |
| 42 | + return { messages, sendMessage }; |
| 43 | +}; |
| 44 | + |
| 45 | +export default usePoll; |
0 commit comments