Coding Question :
Implement an input field that fetches suggestions from an API as the user types, but only sends the request when the user stops typing for a specified amount of time
Explanation
Debounce Function:
- The
debounce
function ensures that thefetchSuggestions
function is only called after a specified delay (500 milliseconds) since the last input change. This prevents excessive API calls when the user types quickly. - It uses a timer (
debounceTimer
) to keep track of the delay. The timer is reset with each keystroke, and only if the user stops typing for 500 milliseconds, the function executes.
- The
Fetch Suggestions:
- The
fetchSuggestions
function makes an asynchronous API call to fetch suggestions based on the input query. - If the query is empty, it returns an empty array to avoid unnecessary API calls.
- It fetches data from
https://api.example.com/suggestions?q=${query}
and returns the suggestions.
- The
DebouncedInput Component:
- State Management: Uses
useState
to managequery
(the input value) andsuggestions
(the fetched suggestions). - Debounced Fetch: The
debouncedFetchSuggestions
function is created usinguseCallback
and thedebounce
function. This memoizes the debounced function, ensuring it remains the same across re-renders. - Effect Hook: The
useEffect
hook monitors changes in thequery
state. When thequery
changes, it calls the debounced fetch function, triggering the API call after the debounce delay. - Input Field: The input field updates the
query
state on every keystroke using theonChange
event handler. - Suggestions List: The component renders a list of suggestions based on the fetched data.
- State Management: Uses
This implementation efficiently handles user input by debouncing API calls, reducing the load on the server, and providing a smoother user experience.