LWC – Handling Multiple API Calls and Merging Responses

Handling Multiple API Calls and Merging Responses in LWC
Chinmaya By Chinmaya
3 Min Read

When working with Lightning Web Components (LWC), you may need to fetch data from multiple APIs and combine their responses before displaying them.

Below are various ways – how you can efficiently handle this scenario.

1. Using Promise.all() for Parallel API Calls

If the API calls are independent and can run in parallel, Promise.all() is the best approach. It waits for all promises to resolve before returning the combined result.

Example:

				
					import { LightningElement, wire } from 'lwc';
import fetchDataFromApi1 from '@salesforce/apex/ApiService.getData1';
import fetchDataFromApi2 from '@salesforce/apex/ApiService.getData2';

export default class MergedApiData extends LightningElement {
    mergedData = [];

    async connectedCallback() {
        try {
            // Make parallel API calls
            const [response1, response2] = await Promise.all([
                fetchDataFromApi1(),
                fetchDataFromApi2()
            ]);

            // Merge responses
            this.mergedData = [...response1, ...response2];
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    }
}
				
			

Advantages

    • Faster execution since calls run in parallel.

    • Clean and concise error handling.

2. Sequential API Calls with async/await

If one API call depends on the response of another, use sequential calls with async/await.

Example

				
					async fetchSequentialData() {
    try {
        const firstResponse = await fetchDataFromApi1();
        const secondResponse = await fetchDataFromApi2({ input: firstResponse.id });
        
        this.mergedData = { ...firstResponse, details: secondResponse };
    } catch (error) {
        console.error('Error in sequential fetch:', error);
    }
}
				
			

When to Use:

    • When API calls have dependencies.

    • When order of execution matters.

3. Error Handling & Loading States

Always handle errors gracefully and provide feedback to users.

				
					isLoading = true;
error;

async fetchData() {
    this.isLoading = true;
    try {
        const results = await Promise.all([apiCall1(), apiCall2()]);
        this.mergedData = processResults(results);
        this.error = undefined;
    } catch (err) {
        this.error = 'Failed to load data.';
        console.error(err);
    } finally {
        this.isLoading = false;
    }
}
				
			

Best Practices:

    • Show a spinner (isLoading).

    • Display error messages if APIs fail.

4. Merging and Transforming Responses

Sometimes API responses need restructuring before use.

				
					// Example: Combining two lists into one
mergeResponses(response1, response2) {
    return {
        users: response1.data,
        posts: response2.data
    };
}
				
			

Conclusion

    • Use Promise.all() for independent parallel calls.

    • Use async/await for sequential dependent calls.

    • Always include error handling and loading states.

    • Transform responses as needed before rendering.

By following these methods, you can efficiently manage multiple API calls in LWC while ensuring a smooth user experience.

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
Leave a comment