Skip to content

TanStack, Viem, Wagmi

TanStack Query

Ref - https://tanstack.com/query/v5/docs/framework/react/overview

Screenshot 2024-10-18 at 2.02.21 PM.png

  • Initialise a react project

    npm create vite@latest
  • Install TanStack Query

npm i @tanstack/react-query
  • Create a fetch function that gets some data
async function getter() {
const data = await fetch("https://jsonplaceholder.typicode.com/posts/");
const response = await data.json();
return response;
}
  • Initialise a new queryClient
const queryClient = new QueryClient()
  • Wrap your app inside a QueryClientProvider
function App() {
return (
// Provide the client to your App
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
  • Define the Todo component
function Todos() {
// Access the client
const queryClient = useQueryClient()
// Queries
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
return (
<div>
<ul>{query.data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
</div>
)
}

Why TanStack?

  1. Caching
  2. Automatic refreshes
  3. Invalidating old states

Try adding a refreshInterval to the query

const query = useQuery({ queryKey: ['todos'], queryFn: getter , refetchInterval: 10 * 1000 })

Notice that every 10s we send out a request to the backend

Screenshot 2024-10-18 at 3.43.04 PM.png

Viem

Screenshot 2024-10-18 at 3.02.14 PM.png

  • Install viem
npm install viem
  • Create a publish client
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'
const client = createPublicClient({
chain: mainnet,
transport: http(),
})
  • Get the current block Number
const blockNumber = await client.getBlockNumber()
  • Get the balance of an address
const balance = await client.getBalance({address: "0x075c299cf3b9FCF7C9fD5272cd2ed21A4688bEeD"})
console.log(balance);