Skip to content

Commit

Permalink
[NO CHANGELOG] [Add Funds Widget] Feat/add funds only set the latest …
Browse files Browse the repository at this point in the history
…route request (#2255)
  • Loading branch information
mimi-imtbl authored Oct 1, 2024
1 parent 70f6b52 commit b666aef
Showing 1 changed file with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ import { TokenBalance } from '@0xsquid/sdk/dist/types';
import { RouteResponse, Token } from '@0xsquid/squid-types';
import { Squid } from '@0xsquid/sdk';
import { utils } from 'ethers';
import { useState } from 'react';
import { useRef, useState } from 'react';
import { delay } from '../functions/delay';
import { AmountData, RouteData } from '../types';

export const useRoutes = () => {
const [routes, setRoutes] = useState<RouteData[]>([]);
const [routes, setRoutes] = useState<RouteData[] | undefined>(undefined);
const latestRequestIdRef = useRef<number>(0); // Track the latest request ID

const resetRoutes = () => {
setRoutes(undefined);
};

const getFromAmount = async (
squid: Squid,
Expand Down Expand Up @@ -101,7 +106,7 @@ export const useRoutes = () => {
toToken: Token,
toAmount: string,
toAddress: string,
fromAddress:string | undefined = undefined,
fromAddress?:string,
quoteOnly = true,
): Promise<RouteResponse | undefined> => {
try {
Expand Down Expand Up @@ -166,6 +171,8 @@ export const useRoutes = () => {
bulkNumber = 5,
delayMs = 1000,
):Promise<RouteData[]> => {
const currentRequestId = ++latestRequestIdRef.current;

const amountDataArray = await getSufficientFromAmounts(
squid,
balances,
Expand All @@ -188,11 +195,14 @@ export const useRoutes = () => {
await delay(delayMs);
}

setRoutes(allRoutes);
// Only update routes if the request is the latest one
if (currentRequestId === latestRequestIdRef.current) {
setRoutes(allRoutes);
}
return allRoutes;
};

return {
routes, fetchRoutesWithRateLimit, getFromAmount, getRoute,
routes, fetchRoutesWithRateLimit, getFromAmount, getRoute, resetRoutes,
};
};

0 comments on commit b666aef

Please sign in to comment.