UNPKG

react-together

Version:

A library to seamlessly add real-time multi-user interaction to your React app!

47 lines (46 loc) 1.17 kB
import { useMultisynqContext as l, usePublish as h } from "@multisynq/react"; import { useState as g, useEffect as b, useCallback as p } from "react"; import { getChat as r } from "../models/ReactTogetherModel.js"; import M from "./useMyId.js"; const u = []; function I(s) { const a = M(), { view: n, model: t } = l(), [m, i] = g(() => { if (!t) return u; const e = r(t, s); return e ? e.messages : u; }); b(() => { if (!t || !n) { i(u); return; } r(t, s) || n.publish(t.id, "createChat", { rtKey: s }); const o = () => { const f = r(t, s); f && i([...f.messages]); }; return o(), n.subscribe(s, "messageSent", o), () => n.unsubscribe(s, "messageSent", o); }, [t, n, s]); const c = h((e) => [s, "sendMessage", e]), d = p( (e) => { if (e.trim() === "") return; const o = Date.now(); if (a === null) { console.warn("Cannot send message outside of a session"); return; } c({ message: e, senderId: a, sentAt: o }); }, [c, a] ); return { messages: m, sendMessage: d }; } export { I as default };