summaryrefslogtreecommitdiff
path: root/apps/web/src/components/providers/global-prefetcher.ts
blob: 2d7c684c323632d1c94fab3f1f35bd4febabfd40 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use client";

import { useEffect } from "react";
import { useSoundsStore } from "@/stores/sounds-store";

export function useGlobalPrefetcher() {
  const {
    hasLoaded,
    setTopSoundEffects,
    setLoading,
    setError,
    setHasLoaded,
    setCurrentPage,
    setHasNextPage,
    setTotalCount,
  } = useSoundsStore();

  useEffect(() => {
    if (hasLoaded) return;

    let ignore = false;

    const prefetchTopSounds = async () => {
      try {
        if (!ignore) {
          setLoading(true);
          setError(null);
        }

        const response = await fetch(
          "/api/sounds/search?page_size=50&sort=downloads"
        );

        if (!ignore) {
          if (!response.ok) {
            throw new Error(`Failed to fetch: ${response.status}`);
          }

          const data = await response.json();
          setTopSoundEffects(data.results);
          setHasLoaded(true);

          // Set pagination state for top sounds
          setCurrentPage(1);
          setHasNextPage(!!data.next);
          setTotalCount(data.count);
        }
      } catch (error) {
        if (!ignore) {
          console.error("Failed to prefetch top sounds:", error);
          setError(
            error instanceof Error ? error.message : "Failed to load sounds"
          );
        }
      } finally {
        if (!ignore) {
          setLoading(false);
        }
      }
    };

    const timeoutId = setTimeout(prefetchTopSounds, 100);

    return () => {
      clearTimeout(timeoutId);
      ignore = true;
    };
  }, [
    hasLoaded,
    setTopSoundEffects,
    setLoading,
    setError,
    setHasLoaded,
    setCurrentPage,
    setHasNextPage,
    setTotalCount,
  ]);
}