Reputation: 10461
I'm creating an autocomplete function, so basically whenever I type on search box it will cancel the previous http get request. I checked the jQuery ui autocomplete and that's what they did. Is that possible in axios if yes how can I implement it. So far here's my code for http get request:
export function autocompleteSearchTest(value){
return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`,{
params: {
q: value
}
})
.then(response => {
return response.data.response;
})
.catch(error => {
const result = error.response;
return Promise.reject(result);
});
}
Here's the screenshot when I type on the search box:
as you can see it doesn't cancel the previous http get request.
Upvotes: 13
Views: 31816
Reputation: 3668
Based on your code, you can cancel token using axios with this
export function autocompleteSearchTest(value){
const cancelToken = axios.CancelToken.source()// 1st
return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`,{
params: {
q: value
}
})
.then(response => {
return response.data.response;
})
.catch(error => {
if (axios.isCancel(e)) return //3rd
const result = error.response;
return Promise.reject(result);
});
return () =>{ // 2nd
cancelToken.cancel();
}
}
Upvotes: 0
Reputation: 141
You can create such a small helper wrapper and use it anywhere where you need to cancel previous request:
// ../services.js
function createApi(baseURL) {
const axiosInst = axios.create({
baseURL,
});
axiosInst.defaults.headers.common['Content-Type'] = 'application/json';
return (type = 'get') => {
let call = null;
return (url, data, config) => {
if (call) {
call.cancel('Only one request allowed!');
}
call = axios.CancelToken.source();
const extConf = {
cancelToken: call.token,
...config,
};
switch (type) {
case 'request':
return axiosInst[type](extConf);
case 'get':
case 'delete':
case 'head':
return axiosInst[type](url, extConf);
default:
return axiosInst[type](url, data, extConf);
}
};
};
}
export const baseApi = createApi('http://localhost:5000/api/')
And then use it anywhere like this:
import baseApi from '../servises.js';
const fetchItemsService = baseApi('post');
//...
componentDidMount() {
fetchItemsService('/items').then(() => {});
}
//...
Upvotes: 1
Reputation: 21
user actions:
import axios from 'axios';
import * as type from 'constants/user';
const CancelToken = axios.CancelToken;
let cancel;
export const addUser = (data) => {
if (cancel !== undefined) cancel();
return ({
types: [type.ADD_USER_REQUEST, type.ADD_USER_SUCCESS, type.ADD_USER_FAILURE],
payload: {
request: {
url: '/api/user',
cancelToken: new CancelToken(c => cancel = c),
method: 'POST',
data,
},
},
});
};
Upvotes: 2
Reputation: 2214
use faxios
// building..
let req = faxios()
.baseURL("http://jsonplaceholder.typicode.com")
.url("posts", 1, "comments")
// fetching..
req // =>
.FETCH // => Promise
.then(res => {})
.catch(err => {});
// canceling...
req.cancel();
Upvotes: 0
Reputation: 73
You wanna use something like RxJS for this, then you can delay the input if the users search, before the requests are made.
Upvotes: 0
Reputation: 3736
Since axios v0.15 you can cancel request:
You can also create a cancel token by passing an executor function to the CancelToken constructor:
var CancelToken = axios.CancelToken;
var cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
For more information please have a look Cancellation. And according to your code:
import React from 'react'
import axios from 'axios';
export function autocompleteSearchTest(value) {
if (cancel != undefined) {
cancel();
}
return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`, {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
}),
params: {
q: value
}
})
.then(response => {
return response.data.response;
})
.catch(error => {
const result = error.response;
return Promise.reject(result);
});
}
var CancelToken = axios.CancelToken;
var cancel;
export class AutoComplete extends React.Component {
constructor() {
super()
this.state = {
search: ''
};
this.handleSearchChange = this.handleSearchChange.bind(this);
}
handleSearchChange(event) {
const target = event.target;
const value = target.value;
this.setState({
search: value
});
autocompleteSearchTest(value)
}
render() {
return (
<div className="App-intro Dialog-section">
<h2>AutoComplete</h2>
<div className="form-control">
<label htmlFor="password">Lookup :</label>
<input name="search" type="text" value={this.state.search}
onChange={this.handleSearchChange}
id="password" ref="password" placeholder="Enter line"/>
</div>
</div>
)
}
}
export default AutoComplete;
Upvotes: 36