aboutsummaryrefslogtreecommitdiffstats
path: root/apps/browser-extension/src/SavePage.tsx
blob: 638af149d810fc9b594946cb65f38f7d0c6e6cdc (plain) (blame)
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { useEffect, useState } from "react";
import Spinner from "./Spinner";
import { api } from "./utils/trpc";
import { Navigate } from "react-router-dom";

export default function SavePage() {
  const [error, setError] = useState<string | undefined>(undefined);

  const {
    data,
    mutate: createBookmark,
    status,
  } = api.bookmarks.createBookmark.useMutation({
    onError: (e) => {
      setError("Something went wrong: " + e.message);
    },
  });

  useEffect(() => {
    async function runSave() {
      let currentUrl;
      const [currentTab] = await chrome.tabs.query({
        active: true,
        lastFocusedWindow: true,
      });
      if (currentTab?.url) {
        currentUrl = currentTab.url;
      } else {
        setError("Couldn't find the URL of the current tab");
        return;
      }

      createBookmark({
        type: "link",
        url: currentUrl,
      });
    }
    runSave();
  }, [createBookmark]);

  switch (status) {
    case "error": {
      return <div className="text-red-500">{error}</div>;
    }
    case "success": {
      return <Navigate to={`/bookmark/${data.id}`} />;
    }
    case "pending": {
      return (
        <div className="flex justify-between text-lg">
          <span>Saving Bookmark </span>
          <Spinner />
        </div>
      );
    }
    case "idle": {
      return <div />;
    }
  }
}