subscribeQuery
stableSubscribe to query state changes
Subscribe to query state changes programmatically. Useful for non-React code, event handlers, and custom state management.
Non-React Usage
subscribeQuery is perfect for non-React code, custom state management, and event handlers.
Memory Leaks
Always call the unsubscribe function to prevent memory leaks. Store it and call it when appropriate.
Signature
function subscribeQuery<TData, TError = Error>(queryKey: QueryKey,callback: (state: QueryState<TData, TError>) => void,options?: QueryOptions<TData>): () => void
Parameters
queryKey
QueryKeyRequiredUnique identifier for the query. Can be a string or array of primitives.
callback
(state: QueryState<TData, TError>) => voidRequiredFunction called whenever the query state changes.
options
QueryOptions<TData>Optional configuration object. If no fetcher is provided, uses a previously registered fetcher.
Returns
Returns
() => voidUnsubscribe function to stop listening to state changes
Examples
Basic Usage
Subscribe to query state changes
import { subscribeQuery } from 'qortex-react';function setupUserSubscription() {// Subscribe to user data changesconst unsubscribe = subscribeQuery(['user', 'current'], (state) => {console.log('User state changed:', {data: state.data,isLoading: state.isLoading,error: state.error});// Handle different statesif (state.isLoading) {console.log('Loading user data...');} else if (state.error) {console.error('Failed to load user:', state.error);} else if (state.data) {console.log('User loaded:', state.data.name);}});// Return unsubscribe function for cleanupreturn unsubscribe;}// Usageconst unsubscribe = setupUserSubscription();// Later, when you want to stop listeningunsubscribe();
Custom State Management
Use in custom state management systems
import { subscribeQuery } from 'qortex-react';class CustomStateManager {private subscriptions: (() => void)[] = [];subscribeToUser(userId: string, onUserChange: (user: any) => void) {const unsubscribe = subscribeQuery(['user', userId], (state) => {if (state.data) {onUserChange(state.data);}});this.subscriptions.push(unsubscribe);return unsubscribe;}subscribeToPosts(onPostsChange: (posts: any[]) => void) {const unsubscribe = subscribeQuery('posts', (state) => {if (state.data) {onPostsChange(state.data);}});this.subscriptions.push(unsubscribe);return unsubscribe;}cleanup() {this.subscriptions.forEach(unsubscribe => unsubscribe());this.subscriptions = [];}}// Usageconst stateManager = new CustomStateManager();stateManager.subscribeToUser('123', (user) => {console.log('User updated:', user);});stateManager.subscribeToPosts((posts) => {console.log('Posts updated:', posts);});// Cleanup when donestateManager.cleanup();
Behavior
State Changes
Calls the callback whenever the query state changes
Non-React
Perfect for non-React code and custom state management
Unsubscribe
Returns an unsubscribe function for cleanup
Type Safe
Provides properly typed state in the callback
Best Practices
Do's
- ✓Always call the unsubscribe function for cleanup
- ✓Use in non-React code and custom state management
- ✓Handle all possible state combinations in the callback
- ✓Use for event handlers and side effects
Don'ts
- ✗Don't use in React components (use useQuery instead)
- ✗Don't forget to unsubscribe to prevent memory leaks
- ✗Don't use for simple one-time operations
- ✗Don't create new functions in the callback on every call