How to make the search value in the input box and the result be preserved when reloading the page (f5) when using reactjs?
Ex: <Input type="text" placeholder={t(‘search_member’)} value={paramsMembers.keyword}
onChange={event => handleOnChangeSearch(event)} className="input-search cursor-pointer" />
i used save to local storage. but this is not true when i switch to another detail page, the initial search value is not "".It gets back the value in local storage
2
Answers
Local storage is definitely the way to go.
If you can provide your code (at least the file that contains what you’re struggling with), it would be easier to find out what went wrong. But based on what you’ve provided, I would suggest you initiate the state of search value using local storage’s value and reset it everytime you switch to other detail pages.
Session storage is designed for persisting this kind of data.
You haven’t shared reproduction steps for the problem that you describe, but it’s possible that simply using session storage alone will resolve it — it depends entirely on your meaning of "switch to another detail page".
You can guarantee that another input’s persisted value won’t appear in a different input by storing them at unique keys in the session storage.
Below I’ve shared a custom hook
useSessionState
that you can use in place of theuseState
hook to persist JSON-serializable values to session storage.Code in the TS Playground
You can see in the
App
function that you use it likeuseState
, except that it takes 2 arguments:The first argument is a key that is unique to a specific input in your app. In the example code, I generated a UUID in advance and used that for the key.
The second argument is the initial value of the state (just like you’d provide to
useState(initialValue)
.Here’s a self-contained HTML file that you can save locally and run in a local http server to verify that it works: