Using SharedPresence in React
useSharedPresence Hello World: Realtime Cursors
// assume current page url: example.com/tomato
import { useSharedPresence, usePersistentNanoId } from '@airstate/react';
export function App() {
const peerId = usePersistentNanoId();
// every client on example.com/tomato is now part of the same room
// and is sharing their state in real-time
const { others, setState } = useSharedPresence({
peerId: peerId, // replace this with any string that uniquely identifies the user
initialState: {
x: 0,
y: 0,
},
});
return (
// a blue 512 x 512 square
<div
className={'absolute bg-blue-200 top-0 left-0 w-[512] h-[512]'}
onMouseMove={(ev) => {
// update dynamic state on mouse move
setState({
x: ev.clientX,
y: ev.clientY,
});
}}>
{/* other people's cursors */}
{Object.values(others).map((other) => (
<div
className={'absolute bg-red-500 w-[2] h-[2] rounded-full'}
style={{
left: other.state.x - 1,
top: other.state.y - 1,
}}></div>
))}
</div>
);
}