telescope icon indicating copy to clipboard operation
telescope copied to clipboard

React Query hooks code possibly can be more simplified

Open Zetazzz opened this issue 2 years ago • 1 comments

Hi, June proposed that React Query hooks code possibly can be more simplified.

  const rpcEndpoint = 'https://rpc.cosmos.directory/cosmoshub';

  const { data: rpcClient } = useRpcClient({
    rpcEndpoint,
    options: {
      enabled: !!rpcEndpoint,
    },
  });

  //@ts-ignore
  // const cosmosHooks = cosmos.ClientFactory.createRPCQueryHooks({ rpc: rpcClient })
  const cosmosHooks = createRpcQueryHooks({ rpc: rpcClient });

  const {
    data: balance,
    isSuccess: isBalanceLoaded,
    isLoading: isFetchingBalance,
    refetch: refetchBalance,
  } = cosmosHooks.cosmos.bank.v1beta1.useBalance({
    request: {
      address: address || '',
      denom: chainassets?.assets[0].base as string,
    },
    options: {
      enabled: !!address && !!rpcClient,
      // transform the returned balance into a BigNumber
      select: ({ balance }) =>
        new BigNumber(balance?.amount ?? 0).multipliedBy(
          10 ** -COIN_DISPLAY_EXPONENT
        ),
    },
  });

Can we make this code less like:

  const cosmosHooks = createRpcQueryHooks({ url: "https://rpc.cosmos.directory/cosmoshub" });

  const {
    data: balance,
    isSuccess: isBalanceLoaded,
    isLoading: isFetchingBalance,
    refetch: refetchBalance,
  } = cosmosHooks.cosmos.bank.v1beta1.useBalance({
    request: {
      address: address || '',
      denom: chainassets?.assets[0].base as string,
    },
    options: {
      enabled: !!address && !!rpcClient,
      // transform the returned balance into a BigNumber
      select: ({ balance }) =>
        new BigNumber(balance?.amount ?? 0).multipliedBy(
          10 ** -COIN_DISPLAY_EXPONENT
        ),
    },
  });

It needs createRpcQueryHooks also accepting url optionally to create RPC client by default.

We discuss the logic here.

Thanks!

Zetazzz avatar Jun 06 '23 04:06 Zetazzz

Cool idea! I think this could be good.

I think we could make another option perhaps? something like createRpcHooksAndClient, as an additional option. But many developers manage their own clients and passing that type of responsibility further down the chain means we lose some control of the RPC client.

I think for the current work we're using this for, we can use the current interface, and then prioritize this a bit after we make progress on our other items, and we can then delete the rpc client code later.

pyramation avatar Jun 06 '23 04:06 pyramation