File size: 2,202 Bytes
5240c42
81969cf
5240c42
6233641
 
5240c42
0891679
03138b9
6233641
 
81969cf
 
 
 
 
 
 
 
0891679
81969cf
5240c42
 
 
848e268
6233641
 
 
 
 
848e268
6233641
 
 
 
 
 
 
03138b9
6233641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03138b9
6233641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5240c42
81969cf
 
 
6233641
 
 
81969cf
5240c42
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 { useMemo, useState } from "react"
import { useQuery, useQueryClient } from "@tanstack/react-query"

import { Collection, Image } from "@/utils/type"
import { useUser } from "@/utils/useUser"

export const useCollection = (id?: string) => {
  const { user, token } = useUser()
  const [loading, setLoading] = useState(false)

  const { data: open } = useQuery(["modal"], () => {
    return null
  }, {
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: false,
    initialData: null
  })
  const setOpen = (id: string | null) => client.setQueryData(["modal"], () => id)

  const client = useQueryClient()

  const collection = useMemo(() => {
    const collections = client.getQueryData<Collection>(["collections"])
    if (!collections?.images) {
      setOpen(null)
      return null
    }
 
    return collections?.images?.find((collection) => collection.id === id)
  }, [id, loading])

  const updateVisibility = async () => {
    setLoading(true)
    const response = await fetch(`/api/collections/${collection?.id}/visibility`, {
      method: "PUT",
      headers: {
        'Authorization': user?.sub ? token : "",
      }
    })

    const data = await response.json()
    if (data.ok) {
      client.setQueryData(["collections"], (old: any) => {
        return {
          ...old,
          images: old.images.map((collection: Image) => {
            if (collection.id === data.image.id) {
              return data.image
            }
            return collection
          })
        }
      })
    }
    setLoading(false)
  }

  const remove = async () => {
    setLoading(true)
    const response = await fetch(`/api/collections/${collection?.id}`, {
      method: "DELETE",
      headers: {
        'Authorization': user?.sub ? token : "",
      }
    })

    const data = await response.json()
    if (data.ok) {
      client.setQueryData(["collections"], (old: any) => {
        return {
          ...old,
          images: old.images.filter((col: Image) => col.id !== collection?.id)
        }
      })
      setOpen(null)
    }
    setLoading(false)
  }

  return {
    collection,
    open,
    setOpen,
    updateVisibility,
    remove
  }
}