2

Background

I am new to ReactJS and needs to create a search field with autocomplete that:

  1. Allows free type
  2. Each user input trigger API request to return a list of matching array
  3. The auto-suggestions should show the latest result

Problem

API response returns in a non-linear order; 1st request could respond later than 2nd request, this caused the State to store not the latest request.

export const SearchBar = () => {

const [state, setState] = useState({list: []})

const apiHandler = (term) => {
  axois.post('www.abc.com',term)
    .then((r)=> {setState({list: r.data})})
}

return(
...
)}

What would be the ways to resolve this?

Thank you.

2 Answers 2

2

as already suggested you should avoid hitting an api for every keystroke with a debouncing strategy. Anyway if you don't care about stressing your server with too many requests you can make use of a ref hook to make sure that the response from the api is still relevant.

I have created a working example with plenty of comments here: https://codesandbox.io/s/awesome-leakey-kil2e?file=/src/App.js

Sign up to request clarification or add additional context in comments.

Comments

2

You should not hit an api on every user input. You have to debounce that function so it delays the call and you can minimize the number of request made to api with good UX.

Lodash Debounce

Also if you are using react you can use this module

use-debounced-effect

you can pass your input variable as dependency.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.