File size: 827 Bytes
423b87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { onDestroy } from "svelte";
import type { Writable } from "svelte/store";
import { writable } from "svelte/store";
import { useRoom } from "./useRoom";

/**
 * Works similarly to `liveblocks-react` useSelf
 * https://liveblocks.io/docs/api-reference/liveblocks-react#useSelf
 *
 * The main difference is that it returns a Svelte store:
 * const self = useSelf()
 * console.log($self.info.id)
 * <div>{$self.info.name}</div>
 */
export function useSelf(): Writable<any> {
  const room = useRoom();
  const self = writable();

  const unsubscribeConnection = room.subscribe("connection", () => {
    self.set(room.getSelf());
  });
  const unsubscribe = room.subscribe("my-presence", () => {
    self.set(room.getSelf());
  });

  onDestroy(() => {
    unsubscribeConnection();
    unsubscribe();
  });

  return self;
}