Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/next/lib/hooks/database.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { useEffect, useState } from "react";67import apiPost from "lib/api/post";8import useIsMounted from "./mounted";9import { removeNulls } from "@cocalc/util/misc";1011export default function useQuery(initialQuery?): {12error: string;13setError: (string) => void; // in case you want to clear the error indicator.14value: any;15loading: boolean;16query: (any) => Promise<any>;17} {18const isMounted = useIsMounted();19const [value, setValue] = useState<any>(initialQuery);20const [error, setError] = useState<string>("");21const [loading, setLoading] = useState<boolean>(!!initialQuery);2223async function query(query) {24setLoading(true);25let result;26try {27result = await apiPost("/user-query", { query });28} catch (err) {29if (!isMounted.current) return;30const error = `${err}`;31setError(error);32setLoading(false);33return { error };34}35if (!isMounted.current) return;36if (result.error) {37setError(result.error);38} else {39setValue(removeNulls(result.query));40}41setLoading(false);42return result;43}4445useEffect(() => {46if (initialQuery) {47query(initialQuery);48}49}, []);5051return { error, value, loading, query, setError };52}535455