import { atom, useAtom } from "jotai"; import { useCallback, useState } from "react"; const roomNameAtom = atom(getRoomNameFromUrl()) function useRoomName() { const [roomName, setRoomName] = useAtom(roomNameAtom) const updateRoomName = useCallback( (newName: string) => { setRoomName(newName); console.log("[Rooms] update room name", newName); }, [setRoomName] ); const updateAndSubmitRoomName = useCallback( (newName: string) => { setRoomName(newName); setRoomNameInUrl(newName); setRoomNameInTitle(newName); console.log("[Rooms] update and submit room name", newName); }, [setRoomName] ) const submitRoomName = useCallback(() => { setRoomNameInUrl(roomName); setRoomNameInTitle(roomName); }, [roomName]); return { roomName, updateRoomName, updateAndSubmitRoomName, submitRoomName }; } function getRoomNameFromUrl(): string { const pathName = location.pathname; const roomName = pathName .substring(pathName.lastIndexOf("/"), pathName.length) .replace("/", ""); console.log("[Rooms] Got roomName from url", roomName); setRoomNameInTitle(roomName); return roomName; } function setRoomNameInUrl(roomName: string) { history.pushState(history.state, "_", roomName); } function setRoomNameInTitle(roomName: string) { if (!!roomName) { document.title = roomName; } } export { useRoomName };