25 lines · 679 B
import { useState } from "react";
import { previewMarkdown } from "~/fns/markdown";

type PreviewState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "ready"; html: string }
  | { status: "error" };

export function useMarkdownPreview(owner: string | null, repo: string | null) {
  const [state, setState] = useState<PreviewState>({ status: "idle" });

  async function load(body: string) {
    setState({ status: "loading" });
    try {
      const result = await previewMarkdown({ data: { owner, repo, body } });
      setState({ status: "ready", html: result.html });
    } catch {
      setState({ status: "error" });
    }
  }

  return { state, load };
}