Created
October 13, 2020 22:51
-
-
Save Flaque/ea3e4414dc640fa7bee34a4c8f3b40da to your computer and use it in GitHub Desktop.
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 { RoomService } from "@roomservice/browser"; | |
import { useEffect, useState } from "react"; | |
const client = new RoomService({ | |
auth: "/api/roomservice", | |
}); | |
function useRoom(name) { | |
const [room, setRoom] = useState(); | |
useEffect(() => { | |
async function load() { | |
const r = await client.room(name); | |
setRoom(r); | |
} | |
load().catch(console.error); | |
}, []); | |
return room; | |
} | |
function useMap(room, mapName) { | |
const [map, setMap] = useState(); | |
useEffect(() => { | |
if (!room) return; | |
const m = room.map(mapName); | |
setMap(m); | |
room.subscribe(m, (nextMap) => { | |
setMap(nextMap); | |
}); | |
}, [room]); | |
return [map, setMap]; | |
} | |
export default function Demo() { | |
const room = useRoom("ibm"); | |
const [map, setMap] = useMap(room, "form"); | |
if (!map) return null; | |
function onChange(e, key) { | |
const nextMap = map.set(key, e.target.value); | |
setMap(nextMap); | |
} | |
return ( | |
<div> | |
<input value={map.get("one")} onChange={(e) => onChange(e, "one")} /> | |
<input value={map.get("two")} onChange={(e) => onChange(e, "two")} /> | |
<input value={map.get("three")} onChange={(e) => onChange(e, "three")} /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment