0

I'm trying to implement a search box, where every time user types something, the search result will show on the page. JS fiddle link : https://jsfiddle.net/wsypeter/dh59Lwr2/47/

here is the code for fetching the data and setting the state basically as I type abc the response might came back in order abc ab a and the result is finally a which is wrong. How should I fix this ? I know one way is to use debounce, but I think it will still run into issue if the response timeout is super long.

This is an interview question, the interviewer said canceling pending request or debouncing is not the solution he's looking for. For the above example , there must be 3 requests going out and the final result should be the response of the last request. How do I do it?

S.W
  • 21
  • 7
  • Why not use a cancel token and cancel any in-flight search requests if more are made? Another solution is to debounce the search so requests are only made after a user stops typing after a small delay. What is `inputText`? Where is it declared, and when is its value set? From what I can see it's likely always equal because the current value of `inputText` is closed over in the same callback scope the request is made in. – Drew Reese Jan 09 '22 at 23:10
  • @DrewReese You meant something like this https://stackoverflow.com/questions/38329209/how-to-cancel-abort-ajax-request-in-axios ? – S.W Jan 09 '22 at 23:17
  • Affirmative, if you are using Axios. `fetch` can sue cancel tokens as well. – Drew Reese Jan 09 '22 at 23:19

1 Answers1

0

You could use debounce for this kind of issue. Only after the user finished typing and hasn't typed anything else for e.g. 500ms then you call the api.

Lin Chen
  • 13
  • 4