We have a site we built using react. There is a search page that does a fetch to our server to get search results in json format. The results are then diplayed. The user then clicks on a result which takes them to another page on our website. Then they click the back button to go back to the search page but now all the results are gone.
If we store the results in localstorage or redux the results will always be there when they go to the search page. So if they go to our home page->search page, when we pull from localstorage they'll be seeing the old stuff.
My question is, is there a way to structure the code so that the results are cached when they do a search but not cached so much that they always appear?
CodePudding user response:
If you have control over the server-side you could simply ensure that the fetch call is cached properly. The JSON response would then be rendered immediately. This is the least invasive solution and would take advantage of the default browser behavior.
If this is not an option, there's a pattern you can follow for client-side caching:
- Save the search results for any given query in redux.
- When the user enters the search page, you display what redux has stored for the search query immediately, and at the same time (when the component mounts) trigger a new search for the same query.
- The search then overwrites what has been cached for the same query in redux.
- If there is nothing cached, the user will have to wait for the first fetch.
- If the results haven't changed since the last fetch, the user simply won't notice anything.
- If the results have changed, the user will see the old cached results for a short period of time (better than nothing, you can still indicate that a new search is in progress) and then the page re-renders, showing the up-to-date results.
Example state:
const searchResultsState = {
'query1': [
{...}, {...}, ... // results
],
'query2': [
{...}, {...}, ... // results
],
};
There are several auxiliary libraries that help with this, but plain react redux thunk is also enough to accomplish this. I think parts of redux-toolkit also embrace this approach. It does make for a very responsive, snappy feeling app to follow such a cache-first approach btw.