Spaces:
Runtime error
Runtime error
import { useState } from "react"; | |
import { useQuery, useQueryClient } from "@tanstack/react-query"; | |
import { useLocalStorage, useUpdateEffect } from "react-use"; | |
import _ from "lodash"; | |
import { useUser } from "@/utils/useUser"; | |
export const useCollections = (category: string) => { | |
const [loading, setLoading] = useState(false); | |
const { user } = useUser(); | |
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({ | |
userId: category === 'my-own' ? user?.sub : undefined, | |
page: 0, | |
}), | |
}) | |
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 response = await fetch("/api/collections", { | |
method: "POST", | |
body: JSON.stringify({ | |
userId: category === 'my-own' ? user?.sub : undefined, | |
page: data?.pagination?.page, | |
}), | |
}) | |
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, | |
} | |
}; |