File size: 1,154 Bytes
6a839c1
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
34
35
36
37
38
39
40
41
42
43
44
45
// @ts-nocheck
import { LiveObject } from "@liveblocks/client";
import { useStorage } from "./useStorage";
import { onDestroy } from "svelte";
import type { Writable } from "svelte/store";
import { writable } from "svelte/store";
import { useRoom } from "./useRoom";

/**
 * Works similarly to `liveblocks-react` useObject
 * https://liveblocks.io/docs/api-reference/liveblocks-react#useObject
 *
 * The main difference is that it returns a Svelte store:
 * const obj = useObject()
 * $obj.set('name', 'Chris')
 * console.log($obj.get('name'))
 */
export function useObject(name: string, initial?: any): Writable<LiveObject> {
  const room = useRoom();
  const rootStore = useStorage();
  const list = writable<LiveObject>();
  let unsubscribe = () => {};

  const unsubscribeRoot = rootStore.subscribe((root) => {
    if (!root) {
      return;
    }

    if (!root.get(name)) {
      root.set(name, new LiveObject(initial));
    }

    list.set(root.get(name));

    unsubscribe();
    unsubscribe = room.subscribe(root.get(name) as LiveObject, (newObject) => {
      list.set(newObject);
    });
  });

  onDestroy(unsubscribeRoot);

  return list;
}