"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const post_1 = __importDefault(require("lib/api/post"));
const mounted_1 = __importDefault(require("./mounted"));
const misc_1 = require("@cocalc/util/misc");
function useQuery(initialQuery) {
    const isMounted = (0, mounted_1.default)();
    const [value, setValue] = (0, react_1.useState)(initialQuery);
    const [error, setError] = (0, react_1.useState)("");
    const [loading, setLoading] = (0, react_1.useState)(!!initialQuery);
    async function query(query) {
        setLoading(true);
        let result;
        try {
            result = await (0, post_1.default)("/user-query", { query });
        }
        catch (err) {
            if (!isMounted.current)
                return;
            const error = `${err}`;
            setError(error);
            setLoading(false);
            return { error };
        }
        if (!isMounted.current)
            return;
        if (result.error) {
            setError(result.error);
        }
        else {
            setValue((0, misc_1.removeNulls)(result.query));
        }
        setLoading(false);
        return result;
    }
    (0, react_1.useEffect)(() => {
        if (initialQuery) {
            query(initialQuery);
        }
    }, []);
    return { error, value, loading, query };
}
exports.default = useQuery;
//# sourceMappingURL=database.js.map