0

I have a text input which value most be unique, to ensure that, I make an API call every time the input changes its value, giving a instantly feedback to the user of whether the input is valid or not.

There are 2 problems with this aproach:

1- Too many innecesary API calls.

2- When the user types fast enought there is a chance that responses came out of order.

For example: If type "foo bar" there will be 7 request checking for: "f","fo","foo","foo ","foo b","foo ba","foo bar" in that exact order. Lets say if "foo ba" is valid but "foo bar" is NOT. If typing is relativly slow it will be ok but if it is fast enough can happend that response from "foo ba" is returned last, meaning the state will be "valid" when it is not

Posible solution will be that any api call cancels all previus calls in progress.

  • Do you compare the value with a huge table? Maybe you can pass data to Vuejs on the page load and let Js check if value is unique. Otherwise, you need to create a settimeout when the input changes. Let's say 500ms. If input changes again before the times up, reset settimeout, otherwise make the request. – Bulent Feb 11 '22 at 20:38
  • Feels like an XY problem. You can use the concept of throttling or denouncing with your API request: only dispatch a request when you’re sure the user has finished typing. This comes with a latency, as user has to wait a little longer, but definitely beats having multiple requests that present a race condition. – Terry Feb 11 '22 at 20:50
  • This is a nice approach https://stackoverflow.com/questions/50516438/cancel-previous-request-using-axios-with-vue-js/53213999 – Armando Rodríguez Acosta Feb 13 '22 at 23:42

1 Answers1

0

I think your hunch that doing a call for every character being wrong is correct. You really should either verify on post that the entry is unique, and if not tell the user. If you want more real time feedback, you could send all the current entries from your DB once on page load, and loop through that on the front end (still not a great solution)

if you are married to your idea, you could solve it as follows:

Generate a unique id for each call and include it in your request.
when you make the call, save that id to a variable, something like lastCall. Every call you make will update the id of last call. Then, when you start getting responses, you only need to react to responses that contain the same id that its in lastCall.

Again, I would recommend changing your approach, but this solution will help fix the issue of calls coming in out of sync. You will still be spamming your backend though.