File size: 2,153 Bytes
848e268
 
6233641
848e268
4f2c36e
63bd9dc
 
cca515d
848e268
5033071
848e268
 
 
5881efa
848e268
 
cca515d
5881efa
 
 
17f8f56
6028520
 
 
17f8f56
 
 
6233641
5033071
6233641
17f8f56
cca515d
17f8f56
5881efa
4f2c36e
5881efa
 
 
848e268
7e19cbb
848e268
 
5881efa
 
 
 
6f0b822
5881efa
 
4f2c36e
848e268
 
17f8f56
6028520
 
 
6407b30
17f8f56
 
6233641
5033071
6233641
17f8f56
 
 
848e268
 
1338bf6
848e268
 
 
 
 
 
 
 
cca515d
 
80165bc
cca515d
4f2c36e
848e268
 
 
 
 
4f2c36e
 
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
79
80
81
82
83
84
85
86
87
88
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useUpdateEffect } from "react-use";
import _ from "lodash";

import { useUser } from "@/utils/useUser";

export const useCollections = (category: string) => {
  const [loading, setLoading] = useState(false);
  const { user, token } = useUser();

  const client = useQueryClient();
  
  const {
    data,
    isFetching,
    refetch,
      } = useQuery(
    ["collections"],
    async () => {
      const queryParams = new URLSearchParams();
      if (category === 'my-own') {
        queryParams.append('userId', user?.sub);
      }
      queryParams.append('page', '0');

      const response = await fetch(`/api/collections?${queryParams.toString()}`, {
        headers: {
          ...(token ? { 'Authorization': token } : {})
        },
        method: "GET",
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.message)
      }
      return {
        images: data?.collections,
        pagination: data?.pagination,
      };
    },
    {
      refetchOnMount: false,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,      
    }
  );

  const infiniteRefetch = async () => {
    setLoading(true);
    const queryParams = new URLSearchParams();
      if (category === 'my-own') {
        queryParams.append('userId', user?.sub);
      }
      queryParams.append('page', data?.pagination?.page + 1);

      const response = await fetch(`/api/collections?${queryParams.toString()}`, {
        headers: {
          ...(token ? { 'Authorization': token } : {})
        },
        method: "GET",
      })

    const d = await response.json()
    if (d.ok) {
      const images = _.concat(data?.images, d?.collections);
      client.setQueryData(["collections"], {
        images,
        pagination: d?.pagination,
      });
    }
    setLoading(false);
  };

  useUpdateEffect(() => {
    refetch()
  }, [category]);

  return {
    images: data?.images,
    loading: isFetching,
    infiniteLoading: loading,
    infiniteRefetch,
    pagination: data?.pagination,
  }
};