This repository has been archived on 2025-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
rpgedit/src/renderer/editor/util.ts

31 lines
663 B
TypeScript

import { useCallback, useEffect, useState } from 'react';
import * as fs from 'fs';
export function usePromise<T>(f: () => Promise<T>): T | null {
const [value, setValue] = useState<T | null>(null);
useEffect(() => {
setValue(null);
let cancelled = false;
(async (): Promise<void> => {
const v = await f();
if (!cancelled) {
setValue(v);
}
})();
return (): void => {
cancelled = true;
};
}, [f]);
return value;
}
export function useReadFile(path: string, encoding: BufferEncoding): string | null {
const readFile = useCallback(() => fs.promises.readFile(path, encoding), [path, encoding]);
return usePromise(readFile);
}