Path: blob/master/src/packages/frontend/conat/use-listing.ts
1503 views
/*1React Hook to provide access to directory listings in a project.23This is NOT used yet, but seems like the right way to do directly listings in a modern4clean dynamic way. It would be used like this:56import useListing from "@cocalc/frontend/conat/use-listing";7function ListingTest({ path, compute_server_id }) {8const listing = useListing({ path, compute_server_id });9return <div>{JSON.stringify(listing)}</div>;10}1112*/1314import { useEffect, useRef, useState } from "react";15import {16listingsClient,17type ListingsClient,18type Listing,19} from "@cocalc/conat/service/listings";20import { useAsyncEffect } from "use-async-effect";21import { useProjectContext } from "@cocalc/frontend/project/context";2223export default function useListing({24path = "",25compute_server_id = 0,26}: {27path: string;28compute_server_id: number;29}): Listing | undefined {30const { project_id } = useProjectContext();31const [listing, setListing] = useState<Listing | undefined>(undefined);32const listingsRef = useRef<undefined | ListingsClient>(undefined);33const pathRef = useRef<string>(path);3435useAsyncEffect(async () => {36setListing(undefined);37if (!project_id) {38return;39}40listingsRef.current = await listingsClient({41project_id,42compute_server_id,43});44const handleChange = (path) => {45if (path == pathRef.current) {46setListing(listingsRef.current?.get(pathRef.current));47}48};49listingsRef.current.on("change", handleChange);5051return () => {52listingsRef.current?.removeListener("change", handleChange);53listingsRef.current?.close();54listingsRef.current = undefined;55};56}, [project_id, compute_server_id]);5758useEffect(() => {59pathRef.current = path;60setListing(listingsRef.current?.get(pathRef.current));61}, [path]);6263return listing;64}656667