portal-dashboard/app/hooks/usePinning.ts

71 lines
2.0 KiB
TypeScript
Raw Normal View History

import { useInvalidate, useNotification } from "@refinedev/core";
2024-03-22 17:53:39 +00:00
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useContext } from "react";
import { PinningProcess } from "~/data/pinning";
import { PinningContext } from "~/providers/PinningProvider";
export const usePinning = () => {
2024-03-22 17:53:39 +00:00
const queryClient = useQueryClient();
const context = useContext(PinningContext);
2024-03-22 17:53:39 +00:00
const { open } = useNotification();
const invalidate = useInvalidate();
2024-03-22 17:53:39 +00:00
const { status: pinStatus, data: pinData, mutate: pinMutation } = useMutation({
2024-03-22 17:53:39 +00:00
mutationKey: ["pin-mutation"],
mutationFn: async (variables: { cid: string }) => {
const { cid } = variables;
const response = await PinningProcess.pin(cid);
2024-03-22 17:53:39 +00:00
if (!response.success) {
open?.({
type: "error",
message: `Error pinning ${cid}`,
description: response.message,
});
}
queryClient.invalidateQueries({ queryKey: ["pin-progress", "file"] });
invalidate({ resource: "files", invalidates: ["list"] });
2024-03-22 17:53:39 +00:00
},
});
const { status: unpinStatus, data: unpinData, mutate: unpinMutation } = useMutation({
2024-03-22 17:53:39 +00:00
mutationKey: ["unpin-mutation"],
mutationFn: async (variables: { cid: string }) => {
const { cid } = variables;
const response = await PinningProcess.unpin(cid);
if (!response.success) {
open?.({
type: "error",
message: `Error removing ${cid}`,
description: response.message,
});
}
queryClient.invalidateQueries({ queryKey: ["pin-progress"] });
invalidate({ resource: "files", invalidates: ["list"] });
2024-03-22 17:53:39 +00:00
},
});
2024-03-22 17:53:39 +00:00
const bulkPin = useCallback(
(cids: string[]) => {
for (const cid of cids) {
pinMutation({ cid });
}
},
[pinMutation],
);
return {
progressStatus: context.query.status,
progressData: context.query.data,
pinStatus,
pinData,
unpinStatus,
unpinData,
2024-03-22 17:53:39 +00:00
pin: pinMutation,
unpin: unpinMutation,
bulkPin,
};
};