Skip to content
This repository was archived by the owner on Jan 14, 2026. It is now read-only.

Commit 2264d09

Browse files
committed
feat: add React Query example with automatic quote fetching
Add a new example project demonstrating TanStack Query (React Query) integration with the Deflex SDK. This advanced example showcases modern data fetching patterns and improved UX over the basic React example. Key features: - Automatic quote fetching with 500ms debounce - Real-time quote updates (refetches every 15 seconds) - `useQuery` hook for quote fetching - `useMutation` hook for swap execution - Improved loading states using debounced amount comparison - No manual "Get Quote" button - quotes fetch automatically - Quotes available without wallet connection (swap requires wallet) Technical changes: - Add `@tanstack/react-query` dependency - Implement `QueryClient` and `QueryClientProvider` in `main.tsx` - Replace manual state management with TanStack Query hooks - Add debounced amount state to prevent excessive API calls - Extract `isFetchingQuote` and `hasValidQuote` computed values - Update button disable logic to use debounced state Documentation: - Add React Query example to root `README.md` - Add React Query section to `examples/README.md` - Create comprehensive README for the example - Include code examples showing `useQuery` and `useMutation` patterns - Document key differences from basic React example Also includes minor CSS fix for account label/address specificity in both React examples (`p.account-label` and `p.account-address` selectors).
1 parent acbdd4e commit 2264d09

File tree

15 files changed

+1043
-60
lines changed

15 files changed

+1043
-60
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ Simple React application demonstrating basic Deflex SDK integration.
2424
- Complete swap UI with quote display
2525
- Fast development with HMR
2626

27+
### [React Query](./examples/react-query)
28+
29+
Advanced React application showcasing TanStack Query integration.
30+
31+
- Automatic quote fetching with debouncing
32+
- Real-time quote updates (refreshes every 15 seconds)
33+
- Optimistic UI updates with mutations
34+
- Demonstrates modern data fetching patterns
35+
2736
### [Node.js CLI](./examples/node-cli)
2837

2938
Command-line tool for executing swaps without a browser.
@@ -68,6 +77,10 @@ Each example can be run independently. Navigate to the example directory and fol
6877
cd examples/react
6978
pnpm dev
7079

80+
# React Query
81+
cd examples/react-query
82+
pnpm dev
83+
7184
# Node.js CLI
7285
cd examples/node-cli
7386
pnpm dev

examples/README.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,22 @@ A simple React application demonstrating basic Deflex SDK integration.
1818

1919
---
2020

21+
### [React Query](./react-query)
22+
23+
An advanced React application showcasing TanStack Query (React Query) integration.
24+
25+
**Key Features:**
26+
27+
- Automatic quote fetching with 500ms debounce
28+
- Real-time quote updates (refreshes every 15 seconds)
29+
- `useQuery` hook for quotes, `useMutation` hook for swaps
30+
- Optimistic UI updates and improved UX
31+
- Demonstrates modern data fetching patterns
32+
33+
[View Example →](./react-query/README.md)
34+
35+
---
36+
2137
### [Node.js CLI](./node-cli)
2238

2339
A command-line tool for executing swaps without a web interface.
@@ -69,6 +85,10 @@ Then run any example:
6985
cd examples/react
7086
pnpm dev
7187

88+
# React Query
89+
cd examples/react-query
90+
pnpm dev
91+
7292
# Node.js CLI
7393
cd examples/node-cli
7494
pnpm dev
@@ -78,7 +98,7 @@ pnpm dev
7898

7999
Each example requires a Deflex API key. Create a `.env` file in the example directory:
80100

81-
### React
101+
### React / React Query
82102

83103
```bash
84104
VITE_DEFLEX_API_KEY=your-api-key-here

examples/react-query/.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
VITE_DEFLEX_API_KEY=your-api-key-here

examples/react-query/README.md

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Deflex SDK - React + TanStack Query Example
2+
3+
A React application demonstrating advanced Deflex SDK integration with TanStack Query (React Query) for automatic quote fetching and optimistic updates.
4+
5+
## Features
6+
7+
- **Automatic quote fetching** - Quotes are fetched automatically when a valid amount is entered
8+
- **Fresh quotes** - Quotes automatically refetch every 15 seconds
9+
- **React Query integration** - Uses `useQuery` for quotes and `useMutation` for swaps
10+
- **Multiple wallet support** (Defly, Pera, Lute)
11+
- **Modern wallet UI** with `@txnlab/use-wallet-react` v4
12+
- **Real-time updates** - No "Get Quote" button needed
13+
- **Execute swaps** with slippage protection
14+
- **Display quote details** and routing information
15+
16+
## Prerequisites
17+
18+
- **Deflex API Key** - Request an API key by emailing [support@txnlab.dev](mailto:support@txnlab.dev)
19+
- Node.js >= 20
20+
- pnpm 10.18.3 or later
21+
22+
## Setup
23+
24+
1. Install dependencies from the repository root:
25+
26+
```bash
27+
pnpm install
28+
```
29+
30+
2. Create a `.env` file in this directory:
31+
32+
```bash
33+
cp .env.example .env
34+
```
35+
36+
3. Add your Deflex API key to the `.env` file:
37+
38+
```
39+
VITE_DEFLEX_API_KEY=your-api-key-here
40+
```
41+
42+
## Development
43+
44+
Run the development server:
45+
46+
```bash
47+
pnpm dev
48+
```
49+
50+
The app will be available at `http://localhost:5173`
51+
52+
## Build
53+
54+
Build for production:
55+
56+
```bash
57+
pnpm build
58+
```
59+
60+
Preview the production build:
61+
62+
```bash
63+
pnpm preview
64+
```
65+
66+
## Usage
67+
68+
1. Choose a wallet from the available options (Defly, Pera, or Lute)
69+
2. Click to connect your chosen wallet
70+
3. If you have multiple accounts, select the active account from the dropdown
71+
4. Select the assets you want to swap
72+
5. Enter the amount and slippage tolerance
73+
6. **Quotes are fetched automatically** - no button needed!
74+
7. Quotes refresh every 15 seconds to ensure you have the latest pricing
75+
8. Review the quote details (output amount, price impact, routing)
76+
9. Click "Execute Swap" to perform the swap
77+
78+
## React Query Integration
79+
80+
This example showcases how to use TanStack Query (React Query) with the Deflex SDK:
81+
82+
### Automatic Quote Fetching
83+
84+
```typescript
85+
const { data: quote, error, isLoading } = useQuery({
86+
queryKey: ['quote', fromAsset, toAsset, amount, activeAddress],
87+
queryFn: async () => {
88+
const deflex = new DeflexClient({ apiKey, autoOptIn: true })
89+
return await deflex.newQuote({
90+
fromASAID: fromAsset,
91+
toASAID: toAsset,
92+
amount: amountInBaseUnits,
93+
address: activeAddress,
94+
})
95+
},
96+
enabled: isValidQuoteRequest(),
97+
refetchInterval: 15000, // Refetch every 15 seconds
98+
})
99+
```
100+
101+
### Swap Execution with Mutations
102+
103+
```typescript
104+
const swapMutation = useMutation({
105+
mutationFn: async () => {
106+
const deflex = new DeflexClient({ apiKey, autoOptIn: true })
107+
const swap = await deflex.newSwap({
108+
quote,
109+
address: activeAddress,
110+
signer: transactionSigner,
111+
slippage: parseFloat(slippage),
112+
})
113+
return await swap.execute()
114+
},
115+
onSuccess: (result) => {
116+
// Handle success
117+
},
118+
})
119+
```
120+
121+
## Key Differences from Basic React Example
122+
123+
1. **No manual "Get Quote" button** - Quotes fetch automatically
124+
2. **Auto-refresh** - Fresh quotes every 15 seconds
125+
3. **React Query hooks** - `useQuery` and `useMutation` replace manual state management
126+
4. **Simplified state** - No `loading` or `executing` state variables needed
127+
5. **Better UX** - Users see quotes immediately as they type
128+
129+
## Wallet Configuration
130+
131+
The example is configured with multiple wallet providers in [src/main.tsx](./src/main.tsx):
132+
133+
```typescript
134+
const walletManager = new WalletManager({
135+
wallets: [WalletId.DEFLY, WalletId.PERA, WalletId.LUTE],
136+
defaultNetwork: 'mainnet',
137+
options: {
138+
resetNetwork: true,
139+
},
140+
});
141+
```
142+
143+
You can customize which wallets are available by modifying this configuration.
144+
145+
## Notes
146+
147+
- This example uses the mainnet by default
148+
- Supports multiple wallets: Defly, Pera, and Lute
149+
- Multi-account support with account switching
150+
- Make sure you have ALGO or the selected asset in your wallet
151+
- The SDK automatically handles asset opt-ins when needed
152+
- Slippage is set to 1% by default but can be adjusted
153+
- Wallet state persists across page refreshes
154+
- Quotes automatically refresh to ensure accurate pricing

examples/react-query/index.html

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Deflex SDK - React Query Example</title>
7+
</head>
8+
<body>
9+
<div id="root"></div>
10+
<script type="module" src="/src/main.tsx"></script>
11+
</body>
12+
</html>

examples/react-query/package.json

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "deflex-example-react-query",
3+
"private": true,
4+
"type": "module",
5+
"scripts": {
6+
"dev": "vite",
7+
"build": "tsc -b && vite build",
8+
"preview": "vite preview"
9+
},
10+
"dependencies": {
11+
"@blockshake/defly-connect": "^1.2.1",
12+
"@perawallet/connect": "^1.4.2",
13+
"@tanstack/react-query": "^5.62.14",
14+
"@txnlab/deflex": "workspace:*",
15+
"@txnlab/use-wallet-react": "^4.3.1",
16+
"lute-connect": "^1.6.3",
17+
"react": "^18.3.1",
18+
"react-dom": "^18.3.1"
19+
},
20+
"devDependencies": {
21+
"@types/react": "^18.3.12",
22+
"@types/react-dom": "^18.3.1",
23+
"@vitejs/plugin-react": "^4.3.4",
24+
"typescript": "~5.6.2",
25+
"vite": "^6.0.5",
26+
"vite-plugin-node-polyfills": "^0.24.0"
27+
}
28+
}

0 commit comments

Comments
 (0)