File size: 1,817 Bytes
848e268
 
cca515d
848e268
4f2c36e
cca515d
848e268
cca515d
848e268
 
 
5881efa
848e268
 
cca515d
5881efa
 
 
cca515d
 
 
 
848e268
cca515d
 
5881efa
4f2c36e
5881efa
 
 
848e268
 
 
 
5881efa
 
 
 
6f0b822
5881efa
 
4f2c36e
848e268
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocalStorage, useUpdateEffect } from "react-use";
import _ from "lodash";

export const useCollections = (category: string) => {
  const [loading, setLoading] = useState(false);
  const [myGenerationsId] = useLocalStorage<any>('my-own-generations', []);

  const client = useQueryClient();
  
  const {
    data,
    isFetching,
    refetch,
      } = useQuery(
    ["collections"],
    async () => {
      const response = await fetch("/api/collections", {
        method: "POST",
        body: JSON.stringify({
          ids: category === 'my-own' ? myGenerationsId : undefined,
          page: 0,
        }),
      })
      const data = await response.json()

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

  const infiniteRefetch = async () => {
    setLoading(true);
    const response = await fetch("/api/collections", {
      method: "POST",
      body: JSON.stringify({
        ids: category === 'my-own' ? myGenerationsId : undefined,
        page: data?.pagination?.page,
      }),
    })
    const d = await response.json()
    if (d.ok) {
      const images = _.concat(data?.images, d?.images);
      client.setQueryData(["collections"], {
        images,
        pagination: d?.pagination,
      });
    }
    setLoading(false);
  };

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

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