Executing Queries in Stack9
Learn how to execute queries in your Stack9 applications using the query service and React hooks. This guide covers the most common patterns for fetching data from your Stack9 backend.
What You'll Learn
- ✅ Using
queryService.runNamedQuery()for direct API calls - ✅ Using
useScreenQueryhook for React components - ✅ Using
useScreenQueryByIdhook for single records - ✅ Implementing pagination, search, and filtering
- ✅ Handling loading states and errors
- ✅ Cache management and data revalidation
- ✅ Best practices and performance optimization
Time Required: 20-30 minutes
Prerequisites
- Completed Custom Queries guide
- Understanding of React hooks
- Queries defined in your Stack9 Query Library
Query Execution Methods
Stack9 provides three primary ways to execute queries:
queryService.runNamedQuery()- Direct API service method (SDK)useScreenQuery()- React hook for list views and complex queries (UI)useScreenQueryById()- React hook for single record by ID (UI)
Method 1: Using queryService.runNamedQuery()
The queryService from @april9au/stack9-sdk provides direct access to execute queries. Use this when:
- You need to execute queries outside of React components
- You're in action types, entity hooks, or server-side code
- You need more control over the request lifecycle
Basic Setup
import { useStack9 } from '@april9au/stack9-react';
function MyComponent() {
const { queryService } = useStack9();
// Now you can use queryService.runNamedQuery()
}
Simple Query Execution
async function loadCustomers() {
const response = await queryService.runNamedQuery(
'customer_list', // Screen key
'getcustomerlist' // Query name
);
console.log(response.data); // Array of customers
}
Query with Variables
async function loadCustomer(customerId: number) {
const response = await queryService.runNamedQuery(
'customer_detail',
'getcustomer',
{
vars: { id: customerId }
}
);
return response.data; // Single customer object
}
Query with Pagination
async function loadProductsPage(page: number, pageSize: number) {
const response = await queryService.runNamedQuery(
'product_list',
'getproductlist',
{
vars: {
page: page,
limit: pageSize
}
}
);
return response.data;
}