<aside> π
https://github.com/djk01281/YJS-SocketIO

YJSλ μνλ₯Ό μΆ©λμμ΄ κ³΅μ ν μ μκ² ν΄μ£Όλ λΌμ΄λΈλ¬λ¦¬λΌκ³ ν μ μμ΅λλ€. μ΄ μνλ₯Ό λ΄μλ 곡κ°μ Y.Docμ΄λΌκ³ ν©λλ€.
λμμ± ν΄κ²°μ μν΄μλ CRDTλ₯Ό μ¬μ©ν©λλ€.
κ°μ₯ κ°λ¨ν μμλ₯Ό μκ°ν΄λ³΄λ©΄, λ€μκ³Ό κ°μ κ² κ°μ΅λλ€.
const toggleMap = {
toggle: true
}
μ΄μ κ°μ objectμ μ¬λ¬ μ¬λμ΄ λμμ μ κ·Όν΄μΌνλ μν©μ
λλ€. κ° ν΄λΌμ΄μΈνΈμλ λ²νΌμ΄ μκ³ , μ΄λ₯Ό λλ¬μ λ²νΌμ μνλ₯Ό ν κΈν΄μ€ μ μμ΅λλ€.
μ€μκ°μΌλ‘ λμν΄μΌ νκΈ° λλ¬Έμ, λ€λ₯Έ ν΄λΌμ΄μΈνΈμμ ν΄λ¦νμ λμ λ³νλ λ°λ‘ μ μ μκ³ λμμ ν΄λ¦νλλΌλ μ΄μ λν μΆ©λμ ν΄κ²°ν΄μ€μΌ ν©λλ€.
[ν΄λΌμ΄μΈνΈ]
μ΄λ₯Ό μν ν΄λΌμ΄μΈνΈ μ½λλ λ€μκ³Ό κ°μ΅λλ€.
import { useEffect, useState, useRef } from "react";
import * as Y from "yjs";
import { SocketIOProvider } from "y-socket.io";
export default function App() {
const [toggle, setToggle] = useState(false);
const ydocRef = useRef<Y.Doc>();
const providerRef = useRef<SocketIOProvider>();
useEffect(() => {
ydocRef.current = new Y.Doc();
const provider = new SocketIOProvider(
"<http://localhost:3000>",
"room-name",
ydocRef.current,
{
autoConnect: true,
disableBc: false,
},
{
reconnectionDelayMax: 10000,
timeout: 5000,
transports: ["websocket", "polling"],
}
);
providerRef.current = provider;
provider.awareness.setLocalState({
user: {
name: `User-${Math.floor(Math.random() * 100)}`,
},
});
const toggleMap = ydocRef.current.getMap("toggleMap");
const updateToggleState = () => {
const newValue = toggleMap.get("toggle");
setToggle(Boolean(newValue));
};
if (!toggleMap.has("toggle")) {
toggleMap.set("toggle", false);
} else {
updateToggleState();
}
toggleMap.observe(() => {
updateToggleState();
});
return () => {
provider.destroy();
ydocRef.current?.destroy();
};
}, []);
const handleToggle = () => {
if (!ydocRef.current) return;
const toggleMap = ydocRef.current.getMap("toggleMap");
const newValue = !toggle;
toggleMap.set("toggle", newValue);
};
return (
<div
style={{
display: "flex",
flexDirection: "column",
gap: "20px",
justifyContent: "center",
alignItems: "center",
width: "100vw",
height: "100vh",
backgroundColor: "#231f20",
}}
>
<button
onClick={handleToggle}
style={{
width: "96px",
height: "96px",
borderRadius: "50%",
transition: "background-color 0.3s",
backgroundColor: toggle ? "#f7b528" : "#e9203d",
border: "none",
cursor: "pointer",
}}
/>
</div>
);
}
μ²μ νλ²λ§ useEffect λ΄λΆμ ν¨μκ° μ€νλ©λλ€.
ydocRef.current = new Y.Doc();
const provider = new SocketIOProvider(
"<http://localhost:3000>",
"room-name",
ydocRef.current,
{
autoConnect: true,
disableBc: false,
},
{
reconnectionDelayMax: 10000,
timeout: 5000,
transports: ["websocket", "polling"],
}
);
providerRef.current = provider;