From 140a9d222f39ca4c27d0e3321a3ce8d54560296c Mon Sep 17 00:00:00 2001 From: Tania Gutierrez Date: Thu, 21 Mar 2024 01:16:27 -0400 Subject: [PATCH] feat: Created PinningContext and PinningProvider to abstract logic from frontend components --- app/hooks/usePinnning.ts | 62 +++++++++++++++++++++++++++++++ app/providers/PinningProvider.tsx | 25 +++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 app/hooks/usePinnning.ts create mode 100644 app/providers/PinningProvider.tsx diff --git a/app/hooks/usePinnning.ts b/app/hooks/usePinnning.ts new file mode 100644 index 0000000..9f55145 --- /dev/null +++ b/app/hooks/usePinnning.ts @@ -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, + }; +}; diff --git a/app/providers/PinningProvider.tsx b/app/providers/PinningProvider.tsx new file mode 100644 index 0000000..b379059 --- /dev/null +++ b/app/providers/PinningProvider.tsx @@ -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> +} + +export const PinningContext = createContext({} as IPinningContextType); + +export const usePinningContext = () => useContext(PinningContext); + +export const PinningProvider = ({ children }: React.PropsWithChildren) => { + const [data, setData] = useState([]); + + return ( + + {children} + + ) +} \ No newline at end of file