Timeout on Axios Requests

Timeout on Axios Requests



Our site currently has a filter feature that fetches new data via axios depending on what is being filtered.



The issue is that the filter is done on real time and every change made via react causes an axios request.



Is there a way to put a timeout on the axios request so that I only fetch the last state?






use a debounce?

– Daniel Lizik
Sep 18 '18 at 1:11




3 Answers
3



The problem has two parts.



The first part is debouncing and is default for event listeners that can be triggered often, especially if their calls are expensive or may cause undesirable effects. HTTP requests fall into this category.



The second part is that if debounce delay is less than HTTP request duration (this is true for virtual every case), there still will be competing requests, responses will result in state changes over time, and not necessarily in correct order.



The first part is addressed with debounce function to reduce the number of competing requests, the second part uses Axios cancellation API to cancel incomplete requests when there's a new one, e.g.:


onChange = e =>
this.fetchData(e.target.value);
;

fetchData = debounce(query =>
if (this._fetchDataCancellation)
this._fetchDataCancellation.cancel();


this._fetchDataCancellation = CancelToken.source();

axios.get(url,
cancelToken: this._fetchDataCancellation.token
)
.then(( data ) =>
this.setState( data );
)
.catch(err =>
// request was cancelled, not a real error
if (axios.isCancel(err))
return;

console.error(err);
);
, 200);



Here is a demo.



I would suggest using debounce in this case to trigger API call after a specified millisecond of user input.


debounce



But just in case you need to add a timeout during axios call, this can be achieved like -


instance.get('/longRequest',
timeout: 5000
);



From this axios issue (Thanks to zhuyifan2013 for giving the solution), I've found that axios timeout is response timeout not connection timeout.


timeout



Please check this answer



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ