| 1 | import type { FromWebviewProtocol } from "core/protocol"; |
| 2 | import type { SuccessWebviewSingleMessage } from "core/protocol/util"; |
| 3 | import { useContext, useEffect, useState } from "react"; |
| 4 | import { IdeMessengerContext } from "../context/IdeMessenger"; |
| 5 | |
| 6 | /** |
| 7 | * Generic hook for making IDE messenger requests with automatic error handling and refresh capability |
| 8 | */ |
| 9 | export function useIdeMessengerRequest<T extends keyof FromWebviewProtocol>( |
| 10 | messageType: T, |
| 11 | data: FromWebviewProtocol[T][0] | null, |
| 12 | ) { |
| 13 | const ideMessenger = useContext(IdeMessengerContext); |
| 14 | const [result, setResult] = useState< |
| 15 | SuccessWebviewSingleMessage<FromWebviewProtocol[T][1]>["content"] | null |
| 16 | >(null); |
| 17 | const [isLoading, setIsLoading] = useState(false); |
| 18 | |
| 19 | async function makeRequest() { |
| 20 | if (!data) { |
| 21 | setResult(null); |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | setIsLoading(true); |
| 26 | try { |
| 27 | const response = await ideMessenger.request(messageType, data); |
| 28 | if (response.status === "success") { |
| 29 | setResult(response.content); |
| 30 | } else { |
| 31 | console.error(`Error in ${messageType} request:`, response.error); |
| 32 | setResult(null); |
| 33 | } |
| 34 | } finally { |
| 35 | setIsLoading(false); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | useEffect(() => { |
| 40 | makeRequest(); |
| 41 | }, [data, messageType]); |
| 42 | |
| 43 | return { result, isLoading, refresh: makeRequest }; |
| 44 | } |