summaryrefslogtreecommitdiffstats
path: root/src/renderer/editor/util.ts
blob: f816de4de0e9afa96f67870e5269141130a643d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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): Buffer | null {
	const readFile = useCallback(() => fs.promises.readFile(path), [path]);
	return usePromise(readFile);
}

export async function readJSON(path: string): Promise<unknown> {
	const content = await fs.promises.readFile(path, 'utf8');
	return JSON.parse(content);
}