Skip to content

Commit

Permalink
feat: add useCreditsForToken
Browse files Browse the repository at this point in the history
  • Loading branch information
fedellen committed Sep 13, 2024
1 parent 6d6f3f9 commit bc29701
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/hooks/useCreditsForToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { TurboFactory } from "@ardrive/turbo-sdk/web";
import { useState, useRef, useEffect } from "react";
import { turboConfig, wincPerCredit } from "../constants";

export function useCreditsForToken(
debouncedTokenAmount: string,
errorCallback: (message: string) => void,
): [string | undefined, string | undefined] {
const [winc, setWinc] = useState<string | undefined>(undefined);
const usdWhenCreditsWereLastUpdatedRef = useRef<string | undefined>(
undefined,
);

// Get credits for USD amount when USD amount has stopped debouncing
useEffect(() => {
TurboFactory.unauthenticated(turboConfig)
.getWincForToken({ tokenAmount: debouncedTokenAmount })
.then(({ winc }) => {
usdWhenCreditsWereLastUpdatedRef.current = debouncedTokenAmount;
setWinc(winc);
})
.catch((err) => {
console.error(err);
errorCallback(`Error getting credits for USD amount: ${err.message}`);
});
}, [debouncedTokenAmount, errorCallback]);

return [
winc ? (+winc / wincPerCredit).toString() : undefined,
usdWhenCreditsWereLastUpdatedRef.current,
];
}

0 comments on commit bc29701

Please sign in to comment.