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: hooks with outdated data or stuck in loading #397

Draft
wants to merge 36 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
bc68557
fix: not updating network data on network changeb
arthurgeron Oct 14, 2024
c3acbda
fix: useAccount not detecting account switches
arthurgeron Oct 14, 2024
77a9001
fix: provider fetching indefinitely or not returning valid provider
arthurgeron Oct 14, 2024
7bdd70d
fix: not updating useWallet with account change
arthurgeron Oct 14, 2024
5f6b1ac
fix: connector not updating on connector change
arthurgeron Oct 14, 2024
66ca2dd
fix: getChain returning outdate data
arthurgeron Oct 14, 2024
1ba5e3d
feat: add new input parameters to watcher keys
arthurgeron Oct 14, 2024
1a15270
fix: avoid including undefined keys
arthurgeron Oct 14, 2024
1348b80
feat: avoid destructuring useQuery return data
arthurgeron Oct 14, 2024
ac067ac
fix: import paths
arthurgeron Oct 14, 2024
57e9b29
feat: update docs
arthurgeron Oct 14, 2024
9573335
feat: accept custom network and chainId in useProvider
arthurgeron Oct 14, 2024
9fbb44d
feat: add support for external isFetching to useNamedQuery
arthurgeron Oct 14, 2024
851fc02
feat: combine isFetching from dependant hooks
arthurgeron Oct 14, 2024
8a4e21f
chore: update docs
arthurgeron Oct 14, 2024
fe4531e
feat: update useWallet when connector changes
arthurgeron Oct 14, 2024
a9348d2
feat: get provider from wallet
arthurgeron Oct 14, 2024
7de8580
fix: import path
arthurgeron Oct 14, 2024
7f17532
fix: remove useProvider dependency from useWallet
arthurgeron Oct 14, 2024
2c086da
feat: create new hook useNetworkProvider
arthurgeron Oct 14, 2024
2e8514b
feat: remove wallet from provider
arthurgeron Oct 14, 2024
5c1d297
chore: remove unecessary fuel event listeners
arthurgeron Oct 14, 2024
f2aea88
fix: useProvider return type
arthurgeron Oct 14, 2024
ca2c43f
feat: rename hook
arthurgeron Oct 14, 2024
36713e8
fix: provider reference
arthurgeron Oct 14, 2024
67564b3
chore: update query key reference
arthurgeron Oct 14, 2024
8cdca67
feat: export useNetworkProvider hook
arthurgeron Oct 14, 2024
c81515b
feat: remove isFetching logic from useNamedQuery
arthurgeron Oct 14, 2024
9b94ca1
chore: update docs
arthurgeron Oct 14, 2024
8451756
chore: minor updates to parameter names
arthurgeron Oct 14, 2024
615f5b1
feat: make sure specific hooks don't depend on account connection
arthurgeron Oct 14, 2024
1459bd3
fix: not updating account status
arthurgeron Oct 14, 2024
8b9a882
chore: changeset
arthurgeron Oct 14, 2024
9ebe044
chore: update memo dependency data
arthurgeron Oct 14, 2024
54d7f94
fix: retry account when invalid
arthurgeron Oct 14, 2024
68a91c8
Merge branch 'main' into ag/fix/fe-751
arthurgeron Oct 15, 2024
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
6 changes: 6 additions & 0 deletions .changeset/nine-chefs-thank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@fuels/react": patch
"docs": patch
---

Fixed hooks with outdated data or stuck in loading
2 changes: 1 addition & 1 deletion packages/docs/src/guide/react-hooks/useAccount.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ console.log(account);
```

#### Defined in
[packages/react/src/hooks/useAccount.ts:26](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useAccount.ts#L26)
[packages/react/src/hooks/useAccount.ts:29](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useAccount.ts#L29)

___
2 changes: 1 addition & 1 deletion packages/docs/src/guide/react-hooks/useChain.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ console.log(chain);
```

#### Defined in
[packages/react/src/hooks/useChain.ts:32](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useChain.ts#L32)
[packages/react/src/hooks/useChain.ts:22](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useChain.ts#L22)

___
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ console.log(currentConnector);
```

#### Defined in
[packages/react/src/hooks/useCurrentConnector.tsx:31](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useCurrentConnector.tsx#L31)
[packages/react/src/hooks/useCurrentConnector.tsx:36](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useCurrentConnector.tsx#L36)

___
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ console.log(isSupportedNetwork);
```

#### Defined in
[packages/react/src/hooks/useIsSupportedNetwork.tsx:29](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useIsSupportedNetwork.tsx#L29)
[packages/react/src/hooks/useIsSupportedNetwork.tsx:30](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useIsSupportedNetwork.tsx#L30)

___
2 changes: 1 addition & 1 deletion packages/docs/src/guide/react-hooks/useNetwork.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ console.log(network);
```

#### Defined in
[packages/react/src/hooks/useNetwork.ts:29](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useNetwork.ts#L29)
[packages/react/src/hooks/useNetwork.ts:36](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useNetwork.ts#L36)

___
2 changes: 1 addition & 1 deletion packages/docs/src/guide/react-hooks/useProvider.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ const { provider } = useProvider();
```

#### Defined in
[packages/react/src/hooks/useProvider.ts:32](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useProvider.ts#L32)
[packages/react/src/hooks/useProvider.ts:37](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useProvider.ts#L37)

___
2 changes: 1 addition & 1 deletion packages/docs/src/guide/react-hooks/useWallet.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ const { wallet } = useWallet();
Use `useWallet({ account })` instead.

#### Defined in
[packages/react/src/hooks/useWallet.ts:53](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useWallet.ts#L53)
[packages/react/src/hooks/useWallet.ts:55](https://github.com/fuellabs/fuel-connectors/blob/main/packages/react/src/hooks/useWallet.ts#L55)
1 change: 1 addition & 0 deletions packages/react/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * from './useConnectors';
export * from './useDisconnect';
export * from './useIsConnected';
export * from './useNetwork';
export * from './useNetworkProvider';
export * from './useNetworks';
export * from './useNodeInfo';
export * from './useProvider';
Expand Down
11 changes: 4 additions & 7 deletions packages/react/src/hooks/useAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,13 @@ export const useAccount = (
const { fuel } = useFuel();

return useNamedQuery('account', {
queryKey: QUERY_KEYS.account(),
queryKey: QUERY_KEYS.account(fuel.name),
queryFn: async () => {
try {
const currentFuelAccount = await fuel?.currentAccount();
return currentFuelAccount;
} catch (_error: unknown) {
return null;
}
return await fuel?.currentAccount();
},
placeholderData: null,
retry: 5,
retryDelay: 100,
...params?.query,
});
};
44 changes: 14 additions & 30 deletions packages/react/src/hooks/useChain.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
// should import ChainInfo because of this error: https://github.com/FuelLabs/fuels-ts/issues/1054
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import type { ChainInfo } from 'fuels';
import type { UseNamedQueryParams } from '../core';

import { useNamedQuery } from '../core';
import { QUERY_KEYS } from '../utils';

import { useProvider } from './useProvider';

type UseChainParams<TName extends string, TData> = {
/**
* Additional query parameters to customize the behavior of `useNamedQuery`.
*/
query?: UseNamedQueryParams<TName, TData, Error, TData>;
};
import { useMemo } from 'react';
import { useNetworkProvider } from './useNetworkProvider';

// @TODO: Add a link to fuel connector's documentation.
/**
Expand All @@ -29,23 +19,17 @@ type UseChainParams<TName extends string, TData> = {
* console.log(chain);
* ```
*/
export const useChain = (
params?: UseChainParams<'chain', ChainInfo | null>,
) => {
const { provider } = useProvider();
export const useChain = () => {
const providerData = useNetworkProvider();
const provider = providerData?.networkProvider;

return useNamedQuery('chain', {
queryKey: QUERY_KEYS.chain(),
queryFn: async () => {
try {
const currentFuelChain = await provider?.getChain();
return currentFuelChain || null;
} catch (_error: unknown) {
return null;
}
},
placeholderData: null,
enabled: !!provider,
...params?.query,
});
return useMemo(() => {
try {
const currentFuelChain = provider?.getChain();
return { chain: currentFuelChain || null };
} catch (e) {
console.error(e);
return { provider: null };
}
}, [provider]);
};
9 changes: 7 additions & 2 deletions packages/react/src/hooks/useCurrentConnector.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { FuelConnector } from 'fuels';
import {
type FuelConnector,
FuelConnectorEventType,
FuelConnectorEventTypes,
} from 'fuels';
import { useEffect } from 'react';
import { type UseNamedQueryParams, useNamedQuery } from '../core';
import { useFuel } from '../providers';
import { QUERY_KEYS } from '../utils';
Expand Down Expand Up @@ -36,7 +41,7 @@ export const useCurrentConnector = <
}: UseCurrentConnectorParams<TName, TData> = {}) => {
const { fuel } = useFuel();
return useNamedQuery('currentConnector', {
queryKey: QUERY_KEYS.currentConnector(),
queryKey: QUERY_KEYS.currentConnector(fuel.name),
queryFn: async () => {
const isConnected = await fuel.isConnected();
if (!isConnected) return null;
Expand Down
63 changes: 42 additions & 21 deletions packages/react/src/hooks/useNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import { useFuel } from '../providers';
import { QUERY_KEYS } from '../utils';
import { useIsConnected } from './useIsConnected';

const TIMEOUT = 500;

type UseNetwork = {
/**
* Additional query parameters to customize the behavior of `useNamedQuery`.
*/
query?: UseNamedQueryParams<'network', Network | null, Error, Network | null>;
query?: Omit<
UseNamedQueryParams<'network', Network | null, Error, Network | null>,
'queryKey' | 'queryFn' | 'refetchInterval'
>;
};

// @TODO: Add a link to fuel connector's documentation.
Expand All @@ -28,25 +33,41 @@ type UseNetwork = {
*/
export const useNetwork = (params?: UseNetwork) => {
const { fuel } = useFuel();
const { isConnected } = useIsConnected();
return useNamedQuery('network', {
queryKey: QUERY_KEYS.currentNetwork(),
queryFn: async () => {
const current = await fuel.currentNetwork();
if (!current && isConnected) {
throw new Error('Network not found');
}
return current;
},
placeholderData: null,
refetchOnMount: true,
refetchInterval: (e) => {
if (!e.state.data || e.state.error) {
return 4000;
}
return false;
const connectedQuery = useIsConnected();
const isConnected = connectedQuery.isConnected;

return useNamedQuery(
'network',
{
queryKey: QUERY_KEYS.currentNetwork(isConnected),
queryFn: async () => {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject('Time out fetching network'), TIMEOUT),
);
const current = await fuel.currentNetwork();
if (!current && isConnected) {
throw new Error('Network not found');
}
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
return Promise.race([current, timeout as any]);
},
placeholderData: null,
refetchOnMount: true,
refetchInterval: (e) => {
if (!e.state.data || e.state.error) {
return TIMEOUT;
}
return false;
},
retry: (attempts) => {
if (attempts > 10) {
return false;
}
return true;
},
enabled: isConnected,
...params?.query,
},
enabled: isConnected,
...params?.query,
});
undefined,
);
};
84 changes: 84 additions & 0 deletions packages/react/src/hooks/useNetworkProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { keepPreviousData } from '@tanstack/react-query';
import { Provider } from 'fuels';
import { type UseNamedQueryParams, useNamedQuery } from '../core';
import { QUERY_KEYS } from '../utils';
import { useNetwork } from './useNetwork';

type UseNetworkProviderParams = {
networkUrl?: string;
chainId?: number;
/**
* Additional query parameters to customize the behavior of `useNamedQuery`.
*/
query?: UseNamedQueryParams<
'networkProvider',
Provider | null,
Error,
Provider | null
>;
};

// @TODO: Add a link to fuel connector's documentation.
/**
* A hook to retrieve the current provider in the connected app.
*
* @returns {object} An object containing:
* - `provider`: The provider data or `null`.
* - {@link https://tanstack.com/query/latest/docs/framework/react/reference/useQuery | `...queryProps`}: Destructured properties from `useQuery` result.
*
* @examples
* To get the current provider:
* ```ts
* const { networkProvider } = useNetworkProvider();
* ```
*/
export const useNetworkProvider = (params?: UseNetworkProviderParams) => {
const networkQuery = useNetwork();
const currentNetwork = networkQuery.network;
const networkUrl = params?.networkUrl || currentNetwork?.url;
const chainId = params?.chainId || currentNetwork?.chainId;

return useNamedQuery(
'networkProvider',
{
queryKey: QUERY_KEYS.networkProvider(networkUrl, chainId),
queryFn: async () => {
async function fetchProvider() {
if (!networkUrl) {
throw new Error(
'Please provide a networks with a RPC url configuration to your FuelProvider getProvider will be removed.',
);
}
const provider = await Provider.create(networkUrl);
if (chainId && provider.getChainId() !== chainId) {
throw new Error(
`The provider's chainId (${provider.getChainId()}) does not match the current network's chainId (${chainId})`,
);
}
return provider;
}

const timeout = new Promise((_, reject) =>
setTimeout(() => reject('Time out fetching provider'), 1000),
) as Promise<Provider | null>;

return Promise.race([fetchProvider(), timeout]);
},
placeholderData: keepPreviousData,
refetchInterval: (e) => {
if (!e.state.data || e.state.error) {
return 500;
}
return false;
},
retry: (attempts) => {
if (attempts > 10) {
return false;
}
return true;
},
...params?.query,
},
undefined,
);
};
6 changes: 3 additions & 3 deletions packages/react/src/hooks/useNodeInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { type UseNamedQueryParams, useNamedQuery } from '../core';
import { QUERY_KEYS } from '../utils';

import type { NodeInfo } from 'fuels';
import { useProvider } from './useProvider';
import { useNetworkProvider } from './useNetworkProvider';

type UseNodeInfoParams = {
/**
Expand Down Expand Up @@ -45,8 +45,8 @@ export const useNodeInfo = ({
version = '0.0.0',
query: queryParams,
}: UseNodeInfoParams = {}) => {
const { provider } = useProvider();

const networkProviderQuery = useNetworkProvider();
const provider = networkProviderQuery.networkProvider;
const query = useNamedQuery('nodeInfo', {
queryKey: QUERY_KEYS.nodeInfo(provider?.url),
queryFn: () => {
Expand Down
Loading
Loading