Search⌘ K

Solution Review: Remember Last Searches

Explore advanced React methods to store and recall your last searches by managing URL states in arrays. Learn to display search terms, create reusable handlers, and ensure efficient data fetching, helping you enhance user experience through better search memory.

We'll cover the following...

Solution

First, we will refactor all url to urls state and all setUrl to setUrls state updater functions. Instead of initializing the state with a url as a string, make it an array with the initial url as its only entry:

Node.js
const App = () => {
...
const [urls, setUrls] = React.useState([
`${API_ENDPOINT}${searchTerm}`,
]);
...
};

Second, instead of using the current url state for data fetching, use the last url entry from the urls array. If another url is added to the list of urls, it is used to fetch data instead:

C++
const App = () => {
...
const handleFetchStories = React.useCallback(async () => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
try {
const lastUrl = urls[urls.length - 1];
const result = await axios.get(lastUrl);
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.data.hits,
});
} catch {
dispatchStories({ type: 'STORIES_FETCH_FAILURE' });
}
}, [urls]);
...
};

And third, instead of storing url string as state with the state updater function, concat the new ...