Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(extension): race condition in activity list [LW-12226] #1736

Merged
merged 2 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/* eslint-disable no-magic-numbers, sonarjs/no-identical-functions, @typescript-eslint/no-empty-function */
import { renderHook, act } from '@testing-library/react-hooks';
import { waitFor } from '@testing-library/react';
import { useAsyncSwitchMap } from '../useAsyncSwitchMap';

jest.useFakeTimers();

describe('useAsyncSwitchMap', () => {
let consoleErrorSpy: jest.SpyInstance;

beforeEach(() => {
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
});

test('calls the callback only for the latest invocation', async () => {
const mockMapper = jest.fn(async (input: number) => {
await new Promise((resolve) => setTimeout(resolve, input * 100));
return input;
});
const mockCallback = jest.fn();

const { result } = renderHook(() => useAsyncSwitchMap(mockMapper, mockCallback));

act(() => {
result.current(1);
result.current(2);
result.current(3);
});

act(() => {
jest.advanceTimersByTime(250);
});

await waitFor(() => expect(mockCallback).toHaveBeenCalledWith(3));

expect(mockMapper).toHaveBeenCalledTimes(3);
expect(mockCallback).toHaveBeenCalledTimes(1);
});

test('handles errors correctly', async () => {
const mockMapper = jest.fn(async (input: number) => {
await new Promise((resolve) => setTimeout(resolve, 100));
if (input === 2) throw new Error('Test Error');
return input * 5;
});
const mockCallback = jest.fn();

const { result } = renderHook(() => useAsyncSwitchMap(mockMapper, mockCallback));

act(() => {
result.current(1);
result.current(2);
result.current(3);
});

act(() => {
jest.advanceTimersByTime(100);
});

await waitFor(() => expect(mockCallback).toHaveBeenCalledWith(15));
expect(mockCallback).toHaveBeenCalledTimes(1);
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
});
});
29 changes: 29 additions & 0 deletions apps/browser-extension-wallet/src/hooks/useAsyncSwitchMap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useCallback, useRef } from 'react';
import { logger } from '@lace/common';

const useAsyncSwitchMap = <TInput, TOutput>(
mapper: (input: TInput) => Promise<TOutput>,
callback: (output: TOutput) => void
): ((input: TInput) => void) => {
const latestCallId = useRef(0);

return useCallback(
(input: TInput) => {
const callId = ++latestCallId.current;

(async () => {
try {
const output = await mapper(input);
if (callId === latestCallId.current) {
callback(output);
}
} catch (error) {
logger.error('useAsyncSwitchMap: Failed to map the input', error);
}
})();
},
[mapper, callback]
);
};

export { useAsyncSwitchMap };
26 changes: 15 additions & 11 deletions apps/browser-extension-wallet/src/hooks/useWalletActivities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { mapWalletActivities } from '@src/stores/slices';
import { Wallet } from '@lace/cardano';
import { AssetActivityListProps, useItemsPageSize } from '@lace/core';
import { useTxHistoryLoader } from './useTxHistoryLoader';
import { useAsyncSwitchMap } from '@hooks/useAsyncSwitchMap';

type UseWalletActivitiesProps = {
sendAnalytics: () => void;
Expand Down Expand Up @@ -121,32 +122,35 @@ export const useWalletActivitiesPaginated = ({
async (history: Wallet.Cardano.HydratedTx[]) => {
const { transactions } = walletState;

return await mapWalletActivities(
{
...walletState,
transactions: { ...transactions, history }
},
fetchActivitiesProps,
fetchActivitiesDeps
);
return (
await mapWalletActivities(
{
...walletState,
transactions: { ...transactions, history }
},
fetchActivitiesProps,
fetchActivitiesDeps
)
).walletActivities;
},
[fetchActivitiesDeps, fetchActivitiesProps, walletState]
);

const handleUpdateWalletActivities = useAsyncSwitchMap(mapActivities, setWalletActivities);

useEffect(() => {
(async () => {
if (loadedHistory?.transactions === undefined || !fiatCurrency || !cardanoFiatPrice) return;

const activities = await mapActivities(loadedHistory.transactions.slice(0, currentPage * pageSize));

setWalletActivities(activities.walletActivities);
handleUpdateWalletActivities(loadedHistory.transactions.slice(0, currentPage * pageSize));
})();
}, [
cardanoFiatPrice,
currentPage,
fetchActivitiesDeps,
fetchActivitiesProps,
fiatCurrency,
handleUpdateWalletActivities,
loadedHistory?.transactions,
mapActivities,
pageSize,
Expand Down
Loading