Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/conat/use-listing.ts
1503 views
1
/*
2
React Hook to provide access to directory listings in a project.
3
4
This is NOT used yet, but seems like the right way to do directly listings in a modern
5
clean dynamic way. It would be used like this:
6
7
import useListing from "@cocalc/frontend/conat/use-listing";
8
function ListingTest({ path, compute_server_id }) {
9
const listing = useListing({ path, compute_server_id });
10
return <div>{JSON.stringify(listing)}</div>;
11
}
12
13
*/
14
15
import { useEffect, useRef, useState } from "react";
16
import {
17
listingsClient,
18
type ListingsClient,
19
type Listing,
20
} from "@cocalc/conat/service/listings";
21
import { useAsyncEffect } from "use-async-effect";
22
import { useProjectContext } from "@cocalc/frontend/project/context";
23
24
export default function useListing({
25
path = "",
26
compute_server_id = 0,
27
}: {
28
path: string;
29
compute_server_id: number;
30
}): Listing | undefined {
31
const { project_id } = useProjectContext();
32
const [listing, setListing] = useState<Listing | undefined>(undefined);
33
const listingsRef = useRef<undefined | ListingsClient>(undefined);
34
const pathRef = useRef<string>(path);
35
36
useAsyncEffect(async () => {
37
setListing(undefined);
38
if (!project_id) {
39
return;
40
}
41
listingsRef.current = await listingsClient({
42
project_id,
43
compute_server_id,
44
});
45
const handleChange = (path) => {
46
if (path == pathRef.current) {
47
setListing(listingsRef.current?.get(pathRef.current));
48
}
49
};
50
listingsRef.current.on("change", handleChange);
51
52
return () => {
53
listingsRef.current?.removeListener("change", handleChange);
54
listingsRef.current?.close();
55
listingsRef.current = undefined;
56
};
57
}, [project_id, compute_server_id]);
58
59
useEffect(() => {
60
pathRef.current = path;
61
setListing(listingsRef.current?.get(pathRef.current));
62
}, [path]);
63
64
return listing;
65
}
66
67