Overview
ThecompositionContactSearch component demonstrates how to create a complete user experience by assembling multiple child components. This advanced composition example includes:
- Integration with Salesforce Apex methods
- Debounced search input handling
- Conditional rendering based on data state
- Error handling and display
- Dynamic iteration over search results
Parent Component Structure
JavaScript (compositionContactSearch.js)
Template (compositionContactSearch.html)
Child Components Used
contactTile Component
Displays individual contact information:errorPanel Component
Handles error display (referenced asc-error-panel):
Key Concepts
Apex Integration
Import and call Apex methods using@salesforce/apex:
Debouncing
Debouncing prevents excessive server calls by delaying execution until user stops typing:- Reduces server load
- Improves user experience
- Prevents race conditions
- Standard delay: 300-500ms
Conditional Rendering
Uselwc:if and lwc:elseif to show different content based on state:
Error Handling
Implement try-catch blocks for async operations:Component Composition Benefits
This example demonstrates several composition advantages:- Reusability:
contactTileanderrorPanelcan be used in other components - Separation of Concerns: Each component has a single responsibility
- Maintainability: Changes to child components don’t affect parent logic
- Testability: Components can be tested independently
- Scalability: Easy to add more child components or features
Data Flow
- User types in search input
handleKeyChangeevent handler is triggered- Debounce timer clears previous timeout and sets new one
- After 350ms delay, Apex method is called
- Results are stored in
contactsproperty orerrorproperty - Template conditionally renders:
- Contact tiles if data exists
- Error panel if error occurred
- Nothing if neither exists (initial state)
Usage Patterns
This pattern is ideal for:- Search interfaces with live results
- Filtered lists with user input
- Dynamic content based on API responses
- Complex UIs requiring multiple component types
- Applications with error handling requirements
Complete Working Example
To implement this pattern:- Create Apex Controller:
-
Create Child Components: Implement
contactTileanderrorPanel - Use Parent Component: Deploy and add to a Lightning page
Best Practices
- Always debounce user input that triggers server calls
- Clear error state when new successful data arrives
- Use conditional rendering to handle different states
- Implement proper error handling for all async operations
- Keep child components focused on single responsibilities
- Use
@apiproperties for all data passed to children
Source Files
- Parent:
force-app/main/default/lwc/compositionContactSearch/ - Child:
force-app/main/default/lwc/contactTile/ - Apex:
force-app/main/default/classes/ContactController.cls
