From 7a69293ba820b432ae117a2e10d943acdc627d8b Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Tue, 8 Feb 2022 00:00:16 +0200 Subject: Add better state management for submit source --- src/api.ts | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) (limited to 'src/api.ts') diff --git a/src/api.ts b/src/api.ts index 226e213..be0c7a1 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,5 +1,6 @@ import useSWR, { SWRResponse } from "swr" import { RunnerApi, ExampleApi } from "slam-types" +import { useState } from "react" const RUNNER_API_URL = String(import.meta.env.VITE_RUNNER_API_URL) const EXAMPLE_API_URL = String(import.meta.env.VITE_EXAMPLE_API_URL) @@ -77,7 +78,7 @@ export const useExamples = () => mapSWRResult -export const submitSource = async (text: string): Promise => { +const postSource = async (text: string): Promise => { const apiResult = await postRequest( { baseUrl: RUNNER_API_URL, @@ -98,3 +99,36 @@ export const submitSource = async (text: string): Promise => { return apiResult } } + +export const useSubmitSource = () => { + const [result, setResult] = useState({ type: "not_yet_requested" }) + + const submitSource = async (text: string) => { + try { + setResult({ type: "loading" }) + const apiResult = await postRequest( + { + baseUrl: RUNNER_API_URL, + path: RunnerApi.SubmitRequest.path, + body: { + source: text, + }, + }, + ) + switch (apiResult.type) { + case "success": + setResult({ type: "success", data: apiResult.data.result }) + break + case "failed": + setResult({ type: "failed", error: apiResult.error }) + break + default: + break + } + } catch (err: any) { + setResult({ type: "failed", error: err }) + } + } + + return { result, submitSource } +} \ No newline at end of file -- cgit v1.3