...

/

Solution Review: Remember Last Searches

Solution Review: Remember Last Searches

Learn to fetch stories for the search term when the button is clicked by recalling last searches.

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:

Press + to interact
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:

Press + to interact
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 ...