Skip to content

Commit

Permalink
Updated the "swr" package
Browse files Browse the repository at this point in the history
  • Loading branch information
Miro Mărgineanu committed Jul 27, 2023
1 parent 276029d commit 1025247
Show file tree
Hide file tree
Showing 4 changed files with 354 additions and 477 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"classnames": "2.3.1",
"platform": "1.3.6",
"qrcode": "1.5.0",
"swr": "1.1.2"
"swr": "2.2.0"
},
"files": [
"*.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const ConfirmReceiver = ({
account: usernameAccount,
loading: usernameAccountLoading,
error: usernameAccountError
} = useGetAccountFromApi(isSmartContract ? null : receiver);
} = useGetAccountFromApi(receiver, { shouldSkipFetching: isSmartContract });

const receiverValue = usernameAccount?.username ?? receiver;
const hasUsername = Boolean(
Expand Down
52 changes: 25 additions & 27 deletions src/hooks/account/useGetAccountFromApi.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,34 @@
import { useEffect, useState } from 'react';
import axios from 'axios';
import useSwr from 'swr';

import { getAccountFromApi } from 'apiCalls';
import { AccountType } from 'types';
import { ACCOUNTS_ENDPOINT } from 'apiCalls';
import { apiAddressSelector } from 'reduxStore/selectors';
import { store } from 'reduxStore/store';

export const useGetAccountFromApi = (address: string | null) => {
const [account, setAccount] = useState<AccountType | null>();
export interface UseGetAccountFromApiOptionsType {
shouldSkipFetching?: boolean;
}

useEffect(() => {
const fetchAccountApi = async (address: string) => {
try {
const accountFromApi = await getAccountFromApi(address);
export const useGetAccountFromApi = (
address: string,
options: UseGetAccountFromApiOptionsType
) => {
const apiAddress = apiAddressSelector(store.getState());
const accountEndpoint = options.shouldSkipFetching
? null
: `${apiAddress}/${ACCOUNTS_ENDPOINT}/${address}`;

setAccount(accountFromApi);
} catch (error) {
console.error(error);
setAccount(null);
}
};
const { data, error, isLoading, isValidating } = useSwr(
accountEndpoint,
(url) => axios.get(url).then((response) => response.data)
);

if (!address) {
setAccount(null);
return;
}

if (address && !account) {
fetchAccountApi(address);
}
}, [address, account]);
const dataLoadingFromLibrary = isLoading || isValidating;
const isUsernameLoading = dataLoadingFromLibrary || (!error && !data);

return {
loading: account === undefined,
error: account === null,
account
loading: isUsernameLoading && !options.shouldSkipFetching,
error,
account: data
};
};
Loading

0 comments on commit 1025247

Please sign in to comment.