In the previous version of the application, every keystroke in the search field triggered a new API request. This behavior can lead to rate limiting and unnecessary network traffic. To prevent this, we implement explicit data fetching — data is only fetched when the user clicks a confirmation button.
First, we add a new button that triggers the search request:
<button
type="button"
disabled={!searchTerm}
onClick={handleSearchSubmit}
>
Submit
</button>We use two states: one for the current input value (searchTerm) and another for the confirmed value that triggers the API request (url):
const [searchTerm, setSearchTerm] = useStorageState('search', 'React');
const [url, setUrl] = React.useState(`${API_ENDPOINT}${searchTerm}`);
const handleSearchInput = (event) => {
setSearchTerm(event.target.value);
};
const handleSearchSubmit = () => {
setUrl(`${API_ENDPOINT}${searchTerm}`);
};We define the data-fetching function using useCallback so it only runs when url changes:
const handleFetchStories = React.useCallback(() => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
fetch(url)
.then((response) => response.json())
.then((result) => {
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.hits,
});
})
.catch(() =>
dispatchStories({ type: 'STORIES_FETCH_FAILURE' })
);
}, [url]);
React.useEffect(() => {
handleFetchStories();
}, [handleFetchStories]);With explicit data fetching in React, API requests are only triggered when the user confirms their search. This approach improves stability, reduces unnecessary network calls, and enhances the overall user experience.