Ronak Khandelwal Ronak Khandelwal - 5 months ago 31
JSON Question

Handling multiple api calls in react-native

I am trying to implement a search field what happens here is whenever user enters text i text field the timer is reset to 300 ms and then an api call(search) is sent to fetch autocomplete results now after receiving those results the app waits for another 1s and sends another request. during this duration the user may enter some more text. So one scenario which I am assuming is that the search api is called and before the response arrives user changes the text sending another pre search call now the response for search arrives and is mistaken for pre search response and hence gives the error. Is there any workaround to this?

Answer

What you want is to cancel the in-flight request when the users enters more text.

I'm assuming you're using the fetch api. Unfortunately it doesn't have a way to cancel the request as per the Promise spec. You can use XMLHttpRequest directly if you need to cancel the request.

Another possibility is to check in the fetch response handler if the initial text being searched has changed. In that case you don't do any action in that handler.

Comments