portal-dashboard/app/hooks/usePinning.ts

63 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2024-03-22 17:53:39 +00:00
import { useNotification } from "@refinedev/core";
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 { mutate: pinMutation } = useMutation({
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,
});
}
2024-03-22 17:53:39 +00:00
queryClient.invalidateQueries({ queryKey: ["pin-progress"] });
},
});
const { mutate: unpinMutation } = useMutation({
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"] });
},
});
2024-03-22 17:53:39 +00:00
const bulkPin = useCallback(
(cids: string[]) => {
for (const cid of cids) {
pinMutation({ cid });
}
},
[pinMutation],
);
return {
...context.query,
2024-03-22 17:53:39 +00:00
pin: pinMutation,
unpin: unpinMutation,
bulkPin,
};
};