Stop Wasting Time: The Ultimate Guide to Efficient API Calls with Redux Saga and Axios!

· 3 min read

Photo by Saif71.com on Unsplash

In modern web development, ensuring efficient and responsive user interfaces is crucial. One common challenge developers face is managing multiple asynchronous requests triggered by user interactions. This article explores how to use Redux Saga with Axios, leveraging the takeLatest effect to abort previous HTTP requests when new ones are made. This approach can significantly improve the performance of your application by avoiding unnecessary network calls.

Introduction to Redux Saga and Axios

Redux Saga is a middleware library designed to handle side effects in Redux applications. It uses generator functions to manage asynchronous actions, making the code more readable and testable. Axios is a popular promise-based HTTP client for making network requests in JavaScript.

Scenario: Handling User Input with Abortable Requests

For this demonstration, I have created a sample page with an input field. As the user types, each keystroke triggers an HTTP request. To prevent multiple unnecessary requests, I use the takeLatest effect from Redux Saga. This ensures only the latest request is processed, and previous ones are aborted.

Note: In real-world applications, especially for search inputs, it’s best practice to implement debounce logic. This example focuses on showcasing _takeLatest_ and request cancellation for demonstration purposes.

Benefits of Using takeLatest with Axios Abort

Using takeLatest in combination with Axios abort functionality provides several benefits:

  1. Improved Performance: By canceling outdated requests, you reduce the load on your server and improve response times.
  2. Resource Efficiency: Network resources are used more efficiently, preventing unnecessary data transfer.
  3. Enhanced User Experience: Users receive the most up-to-date information without experiencing delays caused by pending requests.

Implementation Details

API Service Configuration

Lets start by configuring API service using Axios. The service includes a cancel token to handle request cancellation.

// src/services/api.js

import axios from "axios";

export const callApi = (
    url,
    method = "get",
    data = null,
    params = {},
    headers = {}
) => {
    const source = axios.CancelToken.source();
    const options = {
        url,
        method,
        params,
        headers,
        cancelToken: source.token,
        data,
    };
    try {
        // Return the promise and the cancel token source immediately
        return {
            promise: axios(options),
            source,
        };
    } catch (error) {
        console.error("Error in API call:", error);
        throw error;
    }
};

Saga to Handle API Requests

Next, create a saga to handle the API requests. This saga uses the callApi function, manages the request lifecycle, and handles cancellation.

// src/store/sagas/apiRequestSaga.js

import { cancelled, put } from "redux-saga/effects";
import { callApi } from "../../services/api";

function* apiRequestSaga({ url, method, data, params, headers, actionType }) {
    // Initiates the API call and gets the promise and cancel source
    const { promise, source } = callApi(url, method, data, params, headers);
    try {
        // Wait for the API response
        const response = yield promise;
        // Dispatch success action with the response data
        yield put({ type: actionType.SUCCESS, payload: response?.data });
    } catch (error) {
        if (error.message === "Request canceled") {
            console.log("Saga was canceled due to a new request");
        } else {
            console.log("Saga was canceled");
        }
        // Dispatch failure action with the error
        yield put({ type: actionType.FAILURE, payload: error });
    } finally {
        // Check if the saga was canceled and handle cancellation
        if (yield cancelled()) {
            console.log("Saga canceled by takeLatest");
            // Cancel the API request if the saga was canceled
            source.cancel("Saga canceled by takeLatest");
        }
    }
}
export default apiRequestSaga;

Demonstration

You can try out the demonstration live on StackBlitz. This example showcases an input field where each keystroke triggers a new request, and previous requests are aborted to ensure only the latest data is fetched.

Try the demo below with Chrome’s network log enabled to observe the request handling.

Try the demo on StackBlitz

For a deeper dive into the implementation, you can explore the code on GitHub: View the project on GitHub

Conclusion

Managing asynchronous requests efficiently is a critical aspect of building performant web applications. Redux Saga’s takeLatest effect, combined with Axios’ ability to abort requests, offers a powerful solution to handle such scenarios. By implementing this approach, you can ensure your application remains responsive and efficient, providing a better experience for your users.

Feel free to explore the provided links and integrate these techniques into your projects to see the benefits firsthand. If you found this article helpful, give it a clap and follow for more insightful content.

Happy coding!

Originally published on Medium .

← Back to blog