Discussion

Cancel Preceded Requests from Frontend side Using Axios

There are some cases that user sends simultaneous requests while preceded requests are still pending. In this case, you will need to cancel the preceding requests.

Axios provides cancelTokenfeature for this purpose.

let cancelToken;
  const handleSearchChange = async (e) => {
    const searchTerm = e.target.value;

    //Check if there are any previous pending requests
    if (typeof cancelToken != typeof undefined) {
      cancelToken.cancel("Operation canceled due to new request.");
    }

    //Save the cancel token for the current request
    cancelToken = axios.CancelToken.source();

    try {
      const results = await axios.get(
        `http://localhost:4000/animals?q=${searchTerm}`,
        { cancelToken: cancelToken.token } //Pass the cancel token to the current request
      );
      console.log("Results for " + searchTerm + ": ", results.data);
    } catch (error) {
      console.log(error);
    }
  };

This stores cancelToken of previous request and use it to cancel the preceded requests with the token value.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *