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/api.ts
Views: 687
import { useEffect, useRef, useState } from "react";1import apiPost from "lib/api/post";2import useIsMounted from "./mounted";3import { delay } from "awaiting";45interface Options {6endpoint: string;7params?: object;8cache_s?: number;9}1011export default function useAPI(12endpoint?: string,13params?: object,14cache_s?: number15) {16const [error, setError] = useState<string>("");17const [result, setResult] = useState<any>(undefined);18const [calling, setCalling] = useState<boolean>(false);19const queue = useRef<Options[]>([]);20const isMounted = useIsMounted();2122async function call(23endpoint1: string | undefined = endpoint,24params1: object | undefined = params,25cache_s1: number | undefined = cache_s26): Promise<any> {27if (endpoint1 == undefined) return;28if (calling) {29queue.current.push({30endpoint: endpoint1,31params: params1,32cache_s: cache_s1,33});34return;35}36setCalling(true);37let result;38try {39result = await apiPost(endpoint1, params1, cache_s);40} catch (err) {41if (!isMounted.current) return;42setCalling(false);43setError(`${err}`);44setResult({ error: err });45queue.current = [];46return;47}48if (!isMounted.current) return;49setCalling(false);50setResult(result);51if (queue.current.length > 0) {52const next = queue.current.shift();53if (next == null) return;54const { endpoint, params, cache_s } = next;55if (!isMounted.current) return;56await delay(1);57call(endpoint, params, cache_s);58}59}6061useEffect(() => {62if (endpoint) {63call(endpoint, params, cache_s);64}65}, [endpoint + JSON.stringify(params)]);6667return { error, result, calling, call };68}697071