Skip to content

Commit

Permalink
use SWR to fetch data in hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
uiii committed Oct 24, 2023
1 parent d6764d6 commit 3e81347
Show file tree
Hide file tree
Showing 14 changed files with 130 additions and 196 deletions.
46 changes: 46 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"react-router-dom": "^6.17.0",
"react-scripts": "5.0.1",
"rollbar": "^2.26.1",
"swr": "^2.2.4",
"ts-custom-error": "^3.3.1",
"typescript": "^4.9.5",
"web-vitals": "^3.3.0"
Expand Down
12 changes: 6 additions & 6 deletions src/components/account/AccountBalancesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ const SortProperties = {
RESERVED: (balance: AccountBalanceWithUsdRate) => balanceSort(balance, "reserved")
};

export type AccountBalanceOverview = {
export type AccountBalancesTable = {
balances: Resource<AccountBalance[]>;
usdRates: Resource<UsdRates>;
}

const AccountBalancesTableAttribute = ItemsTableAttribute<AccountBalance, SortProperty<AccountBalance>, [UsdRates]>;
const AccountBalancesTableAttribute = ItemsTableAttribute<AccountBalance, SortProperty<AccountBalance>, [UsdRates|undefined]>;

export const AccountBalancesTable = (props: AccountBalanceOverview) => {
export const AccountBalancesTable = (props: AccountBalancesTable) => {
const { balances, usdRates } = props;

const [sort, setSort] = useState<SortOrder<SortProperty<AccountBalanceWithUsdRate>>>({
Expand Down Expand Up @@ -170,7 +170,7 @@ export const AccountBalancesTable = (props: AccountBalanceOverview) => {
amount={balance.balance.total}
currency={balance.network.symbol}
decimalPlaces="optimal"
usdRate={usdRates[balance.network.name]}
usdRate={usdRates?.[balance.network.name]}
showFullInTooltip
showUsdValue
data-test={`${balance.network.name}-balance-total`}
Expand Down Expand Up @@ -203,7 +203,7 @@ export const AccountBalancesTable = (props: AccountBalanceOverview) => {
amount={balance.balance.free}
currency={balance.network.symbol}
decimalPlaces="optimal"
usdRate={usdRates[balance.network.name]}
usdRate={usdRates?.[balance.network.name]}
showFullInTooltip
showUsdValue
data-test={`${balance.network.name}-balance-free`}
Expand All @@ -222,7 +222,7 @@ export const AccountBalancesTable = (props: AccountBalanceOverview) => {
amount={balance.balance.reserved}
currency={balance.network.symbol}
decimalPlaces="optimal"
usdRate={usdRates[balance.network.name]}
usdRate={usdRates?.[balance.network.name]}
showFullInTooltip
showUsdValue
data-test={`${balance.network.name}-balance-reserved`}
Expand Down
6 changes: 5 additions & 1 deletion src/components/account/AccountPortfolio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ export const AccountPortfolio = (props: AccountPortfolioProps) => {
}

if (balances.notFound || stats.total.eq(0)) {
return <NotFound css={notFoundStyle}>No positive balances with conversion rate to USD found</NotFound>;
return (
<NotFound css={notFoundStyle}>
No positive balances with conversion rate to USD found
</NotFound>
);
}

if (balances.error) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/account/AccountPortfolioChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export enum AccountPortfolioChartMode {

export type AccountPortfolioChartProps = HTMLAttributes<HTMLDivElement> & {
balances: AccountBalance[];
usdRates: UsdRates;
usdRates?: UsdRates;
mode: AccountPortfolioChartMode;
};

Expand Down
8 changes: 4 additions & 4 deletions src/components/balances/BalancesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type BalancesTableProps = {
usdRates: Resource<UsdRates>;
};

const BalancesItemsTableAttribute = ItemsTableAttribute<Balance, never, [UsdRates]>;
const BalancesItemsTableAttribute = ItemsTableAttribute<Balance, never, [UsdRates|undefined]>;

function BalancesTable(props: BalancesTableProps) {
const { network, balances, usdRates } = props;
Expand Down Expand Up @@ -50,7 +50,7 @@ function BalancesTable(props: BalancesTableProps) {
amount={balance.total}
currency={network.symbol}
decimalPlaces="optimal"
usdRate={usdRates[network.name]}
usdRate={usdRates?.[network.name]}
showFullInTooltip
showUsdValue
/>
Expand All @@ -64,7 +64,7 @@ function BalancesTable(props: BalancesTableProps) {
amount={balance.free}
currency={network.symbol}
decimalPlaces="optimal"
usdRate={usdRates[network.name]}
usdRate={usdRates?.[network.name]}
showFullInTooltip
showUsdValue
/>
Expand All @@ -78,7 +78,7 @@ function BalancesTable(props: BalancesTableProps) {
amount={balance.reserved}
currency={network.symbol}
decimalPlaces="optimal"
usdRate={usdRates[network.name]}
usdRate={usdRates?.[network.name]}
showFullInTooltip
showUsdValue
/>
Expand Down
115 changes: 20 additions & 95 deletions src/hooks/usePaginatedResource.ts
Original file line number Diff line number Diff line change
@@ -1,111 +1,36 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRollbar } from "@rollbar/react";
import { useMemo } from "react";

import { FetchOptions } from "../model/fetchOptions";
import { ItemsResponse } from "../model/itemsResponse";
import { PaginatedResource } from "../model/paginatedResource";
import { PaginationOptions } from "../model/paginationOptions";
import { DataError } from "../utils/error";

import { usePagination } from "./usePagination";

type PaginatedResourceProps<T> = Omit<PaginatedResource<T>, "notFound" | "pagination" | "refetch">;

const defaultResourceProps = {
data: [],
totalCount: undefined,
loading: true,
error: undefined,
};
import { useResource } from "./useResource";

export function usePaginatedResource<T = any, F extends any[] = any[]>(
fetchItems: (...args: [...F, PaginationOptions]) => ItemsResponse<T>|Promise<ItemsResponse<T>>,
args: F,
options?: FetchOptions
options: FetchOptions = {}
) {
const rollbar = useRollbar();

const fetchRequestKey = useMemo(() => JSON.stringify(args), [JSON.stringify(args)]);
const previousFetchRequestKeyRef = useRef<string>();

const [resourceProps, setResourceProps] = useState<PaginatedResourceProps<T>>(defaultResourceProps);

const pagination = usePagination();

const fetchData = useCallback(async () => {
if (options?.waitUntil) {
// wait until all required condition are met
return;
const resource = useResource(fetchItems, [...args, {
limit: pagination.limit,
offset: pagination.offset
}], {
...options,
onSuccess: (data) => {
data && pagination.set(data.pagination);
}

if (!options?.skip) {
try {
const items = await fetchItems(...args, {
limit: pagination.limit,
offset: pagination.offset,
});

setResourceProps((props) => ({
...props,
data: items.data,
totalCount: items.totalCount
}));

pagination.set(items.pagination);
} catch(error) {
if (error instanceof DataError) {
rollbar.error(error);
setResourceProps((props) => ({
...props,
error
}));
} else {
throw error;
}
}
}

setResourceProps((props) => ({
...props,
loading: false
}));
}, [
fetchItems,
fetchRequestKey,
pagination.limit,
pagination.offset,
options?.skip,
]);

useEffect(() => {
setResourceProps((props) => ({
...props,
data: [],
error: undefined,
loading: true
}));
fetchData();
}, [fetchData]);

return useMemo<PaginatedResource<T>>(
() => {
if (previousFetchRequestKeyRef.current && previousFetchRequestKeyRef.current !== fetchRequestKey) {
// do not return old data if the fetch args changed
return ({
...defaultResourceProps,
notFound: false,
pagination,
refetch: fetchData
});
}

return ({
...resourceProps,
notFound: !resourceProps.loading && !resourceProps.error && (!resourceProps.data || resourceProps.data.length === 0),
pagination,
refetch: fetchData
});
},
[fetchRequestKey, resourceProps, pagination, fetchData]
);
});

return useMemo<PaginatedResource<T>>(() => ({
data: resource.data?.data,
totalCount: resource.data?.totalCount,
loading: resource.loading,
notFound: resource.notFound || resource.data?.data.length === 0,
error: resource.error,
pagination,
}), [resource, pagination]);
}
Loading

0 comments on commit 3e81347

Please sign in to comment.