swr#SWRResponse TypeScript Examples

The following examples show how to use swr#SWRResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useEtherSWR.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
function useEtherSWR<Data = any, Error = any>(
  ...args: any[]
): SWRResponse<Data, Error> {
  // @ts-ignore - TS gets confused here about the number of args
  const swrResponse = useEtherSWRHook<Data, Error>(...args);
  const { chainId } = useWeb3React();

  const prevChainId = usePrevious(chainId);
  useEffect(() => {
    if (prevChainId && chainId !== prevChainId) {
      swrResponse.mutate(null);
    }
  }, [chainId, prevChainId, swrResponse]);

  return swrResponse;
}
Example #2
Source File: useContract.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useContractCall = (
  address: string,
  abi: any[],
  functionName: string,
  params: string[]
): SWRResponse => {
  return useContractCalls([
    {
      address,
      abi,
      functionName,
      params,
    },
  ]);
}
Example #3
Source File: useContract.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useContractCalls = (
  calls: {
    address: string;
    abi: any[];
    functionName: string;
    params: string[];
  }[]
): SWRResponse => {
  return useEtherSWR(
    calls.map(call => {
      return [call.address, call.functionName, ...call.params];
    }),
    {
      ABIs: new Map(calls.map(call => [call.address, call.abi])),
    }
  );
}
Example #4
Source File: useGithubReleases.ts    From website with Apache License 2.0 6 votes vote down vote up
useGithubReleases = () => {
  const { data, error }: SWRResponse<Releases, Error> = useSWR(
    "https://api.github.com/repos/dahliaOS/releases/releases",
  );

  return {
    releases: data,
    isLoading: !error && !data,
    isError: error,
  };
}
Example #5
Source File: useGuildConfig.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
useGuildConfig = (
  guildAddress: string
): SWRResponse<GuildConfig> => {
  const { data, error, isValidating, mutate } = useEtherSWR(
    guildAddress
      ? [
          [guildAddress, 'getPermissionRegistry'], // Get the address of the permission registry contract
          [guildAddress, 'getName'], // Get the name of the ERC20Guild
          [guildAddress, 'getProposalTime'], // Get the proposalTime (seconds)
          [guildAddress, 'getTimeForExecution'], // Get the timeForExecution (seconds)
          [guildAddress, 'getMaxActiveProposals'], // Get the maxActiveProposals
          [guildAddress, 'getVotingPowerForProposalCreation'],
          [guildAddress, 'getVotingPowerForProposalExecution'],
          [guildAddress, 'getTokenVault'],
          [guildAddress, 'getLockTime'],
        ]
      : [],
    {
      ABIs: new Map([[guildAddress, ERC20GuildContract.abi]]),
      refreshInterval: 0,
    }
  );
  const { data: token } = useGuildToken(guildAddress);
  const { data: totalLocked } = useTotalLocked(guildAddress);

  // TODO: Move this into a SWR middleware
  const transformedData = useMemo(() => {
    if (!data) return undefined;

    const [
      permissionRegistry,
      name,
      proposalTime,
      timeForExecution,
      maxActiveProposals,
      votingPowerForProposalCreation,
      votingPowerForProposalExecution,
      tokenVault,
      lockTime,
    ] = data;

    return {
      permissionRegistry,
      name,
      proposalTime: BigNumber.from(proposalTime),
      timeForExecution: BigNumber.from(timeForExecution),
      maxActiveProposals: BigNumber.from(maxActiveProposals),
      votingPowerForProposalCreation: BigNumber.from(
        votingPowerForProposalCreation
      ),
      votingPowerForProposalExecution: BigNumber.from(
        votingPowerForProposalExecution
      ),
      tokenVault,
      lockTime: BigNumber.from(lockTime),
    };
  }, [data]);

  return {
    error,
    isValidating,
    mutate,
    data: transformedData
      ? { ...transformedData, totalLocked, token }
      : undefined,
  };
}
Example #6
Source File: useEtherSWR.ts    From ether-swr with MIT License 4 votes vote down vote up
function useEtherSWR<Data = any, Error = any>(
  ...args: any[]
): SWRResponse<Data, Error> {
  let _key: ethKeyInterface
  let fn: any //fetcherFn<Data> | undefined
  let config: EthSWRConfigInterface<Data, Error> = { subscribe: [] }
  let isMulticall = false
  if (args.length >= 1) {
    _key = args[0]
    isMulticall = Array.isArray(_key[0])
  }
  if (args.length > 2) {
    fn = args[1]
    //FIXME we lost default value subscriber = []
    config = args[2]
  } else {
    if (typeof args[1] === 'function') {
      fn = args[1]
    } else if (typeof args[1] === 'object') {
      config = args[1]
    }
  }

  config = Object.assign({}, useContext(EthSWRConfigContext), config)

  if (fn === undefined) {
    fn = config.fetcher || etherJsFetcher(config.web3Provider, config.ABIs)
  }

  // TODO LS implement a getTarget and change subscribe interface {subscribe: {name: "Transfer", target: 0x01}}
  const [target] = isMulticall
    ? [_key[0][0]] // pick the first element of the list.
    : _key

  const { cache } = useSWRConfig()
  // we need to serialize the key as string otherwise
  // a new array is created everytime the component is rendered
  // we follow SWR format
  const normalizeKey = isMulticall ? JSON.stringify(_key) : _key

  // base methods (e.g. getBalance, getBlockNumber, etc)
  useEffect(() => {
    if (!config.web3Provider || !config.subscribe || Array.isArray(target)) {
      // console.log('skip')
      return () => ({})
    }
    // console.log('effect!')
    const contract = buildContract(target, config)

    const subscribers = Array.isArray(config.subscribe)
      ? config.subscribe
      : [config.subscribe]

    const instance: Contract | Provider = contract || config.web3Provider

    subscribers.forEach(subscribe => {
      let filter
      const internalKey = unstable_serialize(normalizeKey)
      if (typeof subscribe === 'string') {
        filter = subscribe
        instance.on(filter, () => {
          // console.log('on(string):', { filter }, Array.from(cache.keys()))
          mutate(internalKey, undefined, true)
        })
      } else if (typeof subscribe === 'object' && !Array.isArray(subscribe)) {
        const { name, topics, on } = subscribe
        const args = topics || []
        filter = contract ? contract.filters[name](...args) : name
        // console.log('subscribe:', filter)
        instance.on(filter, (...args) => {
          if (on) {
            // console.log('on(object):', { filter }, Array.from(cache.keys()))
            on(cache.get(internalKey), ...args)
          } else {
            // auto refresh
            // console.log('auto(refresh):', { filter }, Array.from(cache.keys()))
            mutate(internalKey, undefined, true)
          }
        })
      }
    })

    return () => {
      subscribers.forEach(filter => {
        instance.removeAllListeners(filter)
      })
    }
  }, [unstable_serialize(normalizeKey), target])

  return useSWR(normalizeKey, fn, config)
}