Last active
July 14, 2022 00:10
-
-
Save HaNdTriX/8c66315773ee93963c178d90f9547c15 to your computer and use it in GitHub Desktop.
Simple shared conflict free peer to peer state via valtio and y.js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Y from "yjs"; | |
import { bindProxyAndYMap } from "valtio-yjs"; | |
import { WebrtcProvider } from "y-webrtc"; | |
import { IndexeddbPersistence } from "y-indexeddb"; | |
import { proxy } from "valtio"; | |
import { useMemo, useEffect } from "react"; | |
type WebrtcProviderOptions = ConstructorParameters<typeof WebrtcProvider>[2]; | |
export default function useRoom<T extends Record<string, unknown>>( | |
roomname: string, | |
password: string | null, | |
initialState: T | |
) { | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
const yDoc = useMemo(() => new Y.Doc(), [roomname, password]); | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
const room = useMemo(() => proxy(initialState), [roomname, password]); | |
// Connect: Webrtc | |
useEffect(() => { | |
const options: Partial<WebrtcProviderOptions> = { | |
password, | |
}; | |
const provider = new WebrtcProvider( | |
roomname, | |
yDoc, | |
options as WebrtcProviderOptions | |
); | |
return () => { | |
provider.destroy(); | |
}; | |
}, [yDoc, roomname, password]); | |
// Connect: IndexDB | |
useEffect(() => { | |
const provider = new IndexeddbPersistence(roomname, yDoc); | |
return () => { | |
provider.destroy(); | |
}; | |
}, [yDoc, roomname]); | |
// Sync to ymap | |
useEffect(() => { | |
const ymap = yDoc.getMap("map"); | |
bindProxyAndYMap(room, ymap); | |
}, [room, yDoc]); | |
return room; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Warning
Deps
Usage
The shape of your State is up to you :)