Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

axios cancel previous request

let cancelToken
2const handleSearchChange = async e => {
3  const searchTerm = e.target.value
4
5  //Check if there are any previous pending requests
6  if (typeof cancelToken != typeof undefined) {
7    cancelToken.cancel("Operation canceled due to new request.")
8  }
9
10  //Save the cancel token for the current request
11  cancelToken = axios.CancelToken.source()
12
13  try {
14    const results = await axios.get(
15      `http://localhost:4000/animals?q=${searchTerm}`,
16      { cancelToken: cancelToken.token } //Pass the cancel token to the current request
17    )
18    console.log("Results for " + searchTerm + ": ", results.data)
19  } catch (error) {
20    console.log(error)
21  }
22}
Source by www.codingdeft.com #
 
PREVIOUS NEXT
Tagged: #axios #cancel #previous #request
ADD COMMENT
Topic
Name
1+5 =