swr-eth
TypeScript icon, indicating that this package has built-in type declarations

0.1.2 • Public • Published

SWR-eth

An util to use SWR with Ethereum

view on npm

export const EthBalance = ({ symbol, address, decimals }) => {
  const { account, library } = useWeb3React<Web3Provider>()
  const { data: balance } = useSWR(['getBalance', 'latest'])
 
  if (!balance) {
    return <div>...</div>
  }
  return (
    <div>
      {parseFloat(formatEther(balance)).toPrecision(4)} {symbol}
    </div>
  )
}

Configure in your project

You can use SWRConfig to have a global fetcher capable of retrieving basic Ethereum information (e.g. block, getBalance) or directly interact with a smart contract

import {ethFetcher } from "swr-eth";
import {SWRConfig} from "swr";
import ERC20ABI from "../abi/ERC20.abi.json";
import {EthBalance} from "./EthBalance";
 
const ABIs = [
  ['0x6b175474e89094c44da98b954eedeac495271d0f', ERC20ABI]
]
 
export const Wallet = () => {
  const { chainId, account, library, activate, active } = useWeb3React<Web3Provider>()
 
  const onClick = () => {
    activate(injectedConnector)
  }
 
  return (
      <div>
        <div>ChainId: {chainId}</div>
        <div>Account: {shorter(account)}</div>
        {active ? (
            <div>✅ </div>
        ) : (
            <button type="button" onClick={onClick}>
              Connect
            </button>
        )}
        {active && (
            <SWRConfig value={{ fetcher: ethFetcher(library, new Map(ABIs)) }}>
              <EthBalance />
              <TokenList chainId={chainId} />
            </SWRConfig>
        )}
      </div>
  )
}

Interact with basic method

const { data: balance } = useSWR(['getBalance', 'latest'])

You can use all the methods provided by a Web3Provider from Ether.js

Interact with a smart contract

const { data: balance } = useSWR(['0x6b175474e89094c44da98b954eedeac495271d0f','balanceOf', 'latest'])

You can use all the methods provided by a contract as long as you have provided the ABI associated to the smat contract address when you configured the ethFetcher

Example

A minimal example is availablehere

Related projects

Licence

Licensed under MIT.

Readme

Keywords

none

Package Sidebar

Install

npm i swr-eth

Weekly Downloads

6

Version

0.1.2

License

MIT

Unpacked Size

11.8 kB

Total Files

22

Last publish

Collaborators

  • aboutlo