-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathhooks.ts
More file actions
36 lines (30 loc) · 979 Bytes
/
hooks.ts
File metadata and controls
36 lines (30 loc) · 979 Bytes
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, useEffectEvent, useState } from "react";
import { getState, setState } from "../api";
/**
* Listen for messages from the extension. No need to memoize the handler.
*/
export function useMessage<T>(handler: (message: T) => void): void {
const onMessage = useEffectEvent((event: MessageEvent<T>): void => {
handler(event.data);
});
useEffect((): (() => void) => {
window.addEventListener("message", onMessage);
return (): void => {
window.removeEventListener("message", onMessage);
};
}, []);
}
/**
* Hook to manage webview state with VS Code's state API
*/
export function useVsCodeState<T>(initialState: T): [T, (state: T) => void] {
const [localState, setLocalState] = useState<T>((): T => {
const saved = getState<T>();
return saved ?? initialState;
});
const setVsCodeState = useCallback((newState: T): void => {
setLocalState(newState);
setState(newState);
}, []);
return [localState, setVsCodeState];
}