feat: Created PinningContext and PinningProvider to abstract logic from frontend components

This commit is contained in:
Tania Gutierrez 2024-03-21 01:16:27 -04:00
parent 52fc50d480
commit 140a9d222f
Signed by: riobuenoDevelops
GPG Key ID: 53133EB28EB7E801
2 changed files with 87 additions and 0 deletions

62
app/hooks/usePinnning.ts Normal file
View File

@ -0,0 +1,62 @@
import { useCustom, useNotification } from "@refinedev/core";
import { usePinningContext } from "~/providers/PinningProvider";
export const usePinning = () => {
const { open } = useNotification();
const { data: cidList, setData } = usePinningContext();
const { data } = useCustom({
// useCustom requires URL and METHOD params
url: "",
method: "get",
dataProviderName: "pinning",
});
const onPin = async (cid: string) => {
if (!data?.pinCid) return;
const response = await data?.pinCid(cid);
if (response.success) {
setData((prev) => [...prev, { cid, progress: 0 }]);
} else {
open?.({
type: "destrunctive",
message: "Erorr pinning " + cid,
description: response.message,
});
}
};
const getProgress = (cid: string) => {
if (!data?.checkCidProgress) return;
const response = data?.checkCidProgress(cid);
if (!response.done) {
setData((prev) =>
prev.map((cidInfo) => {
const newData = cidInfo;
if (cidInfo.cid === cid) {
newData.progress = response.value.progress;
return newData;
}
return cidInfo;
}),
);
}
};
const onRemoveCidFromList = (cid: string) => {
setData((prev) => prev.filter((item) => item.cid !== cid));
};
return {
cidList,
onPin,
getProgress,
onRemoveCidFromList,
};
};

View File

@ -0,0 +1,25 @@
import { Dispatch, SetStateAction, createContext, useContext, useState } from "react";
export interface IPinningData {
cid: string;
progress: number
}
export interface IPinningContextType {
data: IPinningData[],
setData: Dispatch<SetStateAction<IPinningData[]>>
}
export const PinningContext = createContext<IPinningContextType>({} as IPinningContextType);
export const usePinningContext = () => useContext(PinningContext);
export const PinningProvider = ({ children }: React.PropsWithChildren) => {
const [data, setData] = useState<IPinningData[]>([]);
return (
<PinningContext.Provider value={{ data, setData }}>
{children}
</PinningContext.Provider>
)
}