CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/lib/hooks/database.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { useEffect, useState } from "react";
7
8
import apiPost from "lib/api/post";
9
import useIsMounted from "./mounted";
10
import { removeNulls } from "@cocalc/util/misc";
11
12
export default function useQuery(initialQuery?): {
13
error: string;
14
setError: (string) => void; // in case you want to clear the error indicator.
15
value: any;
16
loading: boolean;
17
query: (any) => Promise<any>;
18
} {
19
const isMounted = useIsMounted();
20
const [value, setValue] = useState<any>(initialQuery);
21
const [error, setError] = useState<string>("");
22
const [loading, setLoading] = useState<boolean>(!!initialQuery);
23
24
async function query(query) {
25
setLoading(true);
26
let result;
27
try {
28
result = await apiPost("/user-query", { query });
29
} catch (err) {
30
if (!isMounted.current) return;
31
const error = `${err}`;
32
setError(error);
33
setLoading(false);
34
return { error };
35
}
36
if (!isMounted.current) return;
37
if (result.error) {
38
setError(result.error);
39
} else {
40
setValue(removeNulls(result.query));
41
}
42
setLoading(false);
43
return result;
44
}
45
46
useEffect(() => {
47
if (initialQuery) {
48
query(initialQuery);
49
}
50
}, []);
51
52
return { error, value, loading, query, setError };
53
}
54
55