Spaces:
Running

attention / frontends /react /src /useTranslation.ts
nhamid289's picture
Deploy from elvis-code (redesigned with the ELVIS design system)
660e352 verified
Raw History Blame Contribute Delete
1.37 kB
import { useEffect, useState } from "react";
import { usePythonStatus } from "@elvis/pyodide";
import { python } from "./python";
import type { Language, Translation } from "./types";
const DEFAULT_SENTENCE = "I will go to school tomorrow.";
// After typing stops, wait this long before translating
const TYPING_DELAY_MS = 500;
export default function useTranslation() {
const status = usePythonStatus(python);
const [sentence, setSentence] = useState(DEFAULT_SENTENCE);
const [language, setLanguage] = useState<Language>("zh");
const [error, setError] = useState<string | null>(null);
// The last sentence that translated, kept while the box holds one that doesn't
const [translation, setTranslation] = useState<Translation | null>(null);
useEffect(() => {
let current = true;
const timer = setTimeout(async () => {
const result = await python.call("handle_translate", {
sentence,
language,
});
if (!current) {
return;
}
setError(result.ok ? null : result.error.message);
if (result.ok) {
setTranslation(result.data);
}
}, TYPING_DELAY_MS);
return () => {
current = false;
clearTimeout(timer);
};
}, [sentence, language]);
return {
status,
sentence,
setSentence,
language,
setLanguage,
error,
translation,
};
}