GoodDollar / GoodWeb3-Mono

mono repo with GoodDollar's web3 UI components and SDK
https://gooddollar-storybook.vercel.app
0 stars 1 forks source link

Make sdkFactory on-demand #77

Closed L03TJ3 closed 1 year ago

L03TJ3 commented 1 year ago
          @L03TJ3 If it won't help then I could suggest to refactor useSDK the following way (splitting it onto 2 hooks):

as this is refactorng, please discuss it with @sirpy !

export const useSDKFactory = (
  readOnly = false,
  type: SdkTypes = "base",
  requiredChainId?: number | undefined,
): any => {
  const { library } = useEthers();
  const { chainId, defaultEnv } = useGetEnvChainId(requiredChainId);
  const rolibrary = useReadOnlyProvider(chainId);

  return useCallback(() =>
    sdkFactory(
      type,
      defaultEnv,
      readOnly,
      library instanceof providers.JsonRpcProvider ? library : undefined,
      rolibrary
    ), [type, defaultEnv, readOnly, library, rolibrary]);
}

export const useSDK = (
  readOnly = false,
  type: SdkTypes = "base",
  requiredChainId?: number | undefined,
): RequestedSdk["sdk"] => {
  const factory = useSDKFactory(readOnly, type, requiredChainId);
  const [sdk, setSdk] = useState<ClaimSDK | SavingsSDK | undefined>(factory);

  // skip first render as sdk already initialized by useState()
  useUpdateEffect(() => void setSdk(factory()), [factory]);
  return sdk;
};

then use factory hook inside useFVLink:

export const useFVLink = (chainId?: number) => {
  const { account } = useEthers();
  const { chainId: defaultChainId } = useGetEnvChainId();
  const sdkFactory = useSDKFactory(false, "claim", chainId ?? defaultChainId);
  const [fvLink, setFVLink] = useState(null);

  useEffect(() => {
    // skip effect if no account
    if (!account) {
      return;
    }

    const sdk = sdkFactory();
    const link = sdk.getFVLink(chainId);

    setFVLink(link);
  }, [account, sdkFactory, chainId]);

  return fvLink;
};

Originally posted by @johnsmith-gooddollar in https://github.com/GoodDollar/GoodWeb3-Mono/issues/70#issuecomment-1460533606

L03TJ3 commented 1 year ago

Currently, there are attempts to initialize an SDK when it should not because there is no account connected The above suggestion is one way how to only do initialization on demand

sirpy commented 1 year ago

I dont see any reason to refactor. the sdk is not actaully being initialized as new SDK() is not being called

L03TJ3 commented 1 year ago

I just dont understand why we would want to go down an entire flow when we now 6 levels up already that is unnecessary to go there