skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. How to make the search value in the input box and the result be preserved when reloading the page (f5) when using reactjs?

    Session storage is designed for persisting this kind of data.

    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

    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 the useState hook to persist JSON-serializable values to session storage.

    Code in the TS Playground

    import { createRoot } from "react-dom/client";
    import {
      type Dispatch,
      type ReactElement,
      type SetStateAction,
      useCallback,
      useEffect,
      useState,
    } from "react";
    
    type JsonValue =
      | boolean
      | null
      | number
      | string
      | JsonValue[]
      | { [key: string]: JsonValue | undefined };
    
    function useSessionState<T extends JsonValue>(
      key: string,
      initialValue: T,
    ): readonly [
      state: T,
      setState: Dispatch<SetStateAction<T>>,
    ] {
      const [state, setState] = useState(initialValue);
    
      useEffect(() => {
        const json = window.sessionStorage.getItem(key);
        if (!json) return;
        try {
          setState(JSON.parse(json));
        } catch (cause) {
          // Wasn't a valid JSON string - Don't update state
          console.warn(
            new Error(
              `Found invalid JSON string in session storage:n${
                JSON.stringify({ key, value: json }, null, 2)
              }`,
              { cause },
            ),
          );
        }
      }, [setState]);
    
      const setter: Dispatch<SetStateAction<T>> = useCallback((valueOrCallback) => {
        setState((previous) => {
          const value = typeof valueOrCallback === "function"
            ? valueOrCallback(previous)
            : valueOrCallback;
          window.sessionStorage.setItem(key, JSON.stringify(value));
          return value;
        });
      }, [setState]);
    
      return [state, setter];
    }
    
    function App(): ReactElement {
      const [text, setText] = useSessionState<string>(
        "3ae3d85d-3521-4ccd-82cb-4c47a4665f16",
        "",
      );
    
      return (
        <div>
          <input
            onChange={(ev) => setText(ev.currentTarget.value)}
            placeholder="Type here then refresh"
            value={text}
          />
        </div>
      );
    }
    
    const rootElement = document.getElementById("root") ??
      document.body.appendChild(document.createElement("div"));
    
    createRoot(rootElement).render(<App />);
    
    

    You can see in the App function that you use it like useState, except that it takes 2 arguments:

      const [text, setText] = useSessionState<string>(
        "3ae3d85d-3521-4ccd-82cb-4c47a4665f16",
        "",
      );
    

    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:

    <!doctype html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
    
      <title>React session state</title>
    
      <!--
        This is necessary for resolving import specifiers in the following module
        script, but you can replace the URLs with your preference
      -->
      <script type="importmap">
        {
          "imports": {
            "react": "https://esm.sh/[email protected]?pin=v130",
            "react-dom": "https://esm.sh/[email protected]?pin=v130",
            "react-dom/client": "https://esm.sh/[email protected]/client?pin=v130",
            "react/jsx-runtime": "https://esm.sh/[email protected]/jsx-runtime?pin=v130"
          }
        }
      </script>
      <!--
        Compiled JS from the TS Playground:
        https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&removeComments=true&target=99&jsx=4&exactOptionalPropertyTypes=true&inlineSourceMap=true&inlineSources=true&isolatedModules=true&noImplicitOverride=true#code/JYWwDg9gTgLgBAbzgYygUwIYzQJQheAXzgDMoIQ4AidDZGAWgBMKB6ZAG2DQDsYqA3AChQkWIiFw4MAJ5g0cACLAAzmCzIAFgBpJ0uQpyZ6AUQ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XGADZaeRkgsdpqgxKoVm9C2uAdq9ACpBBJhgDXZFOJBKYwACGAst8EJNE6KN6gQVEysC9UYF+mFlbXQNkGLdA+DBZ9Y0DKapMIsAODoNBNHvO4oHqKgwQMOBNBGBQYFdr10DIP5NEywi7MVz6YDNidWBF8sQVYQXhc5k7ije7n8Ee8xLD4b0WF1tOYBjZwnuzgAhGQ4yYVEaGTqg7Wy7K9EzgJs8DNomBkQMMGu3gmFl4AOFLuuG9QTBsHzqwy5jyulIH9w8AIVFyAIYe+EpQN9bt1EQSusA4HD1MgA
      -->
      <script type="module">
        import { jsx as _jsx } from "react/jsx-runtime";
        import { createRoot } from "react-dom/client";
        import { useCallback, useEffect, useState, } from "react";
        function useSessionState(key, initialValue) {
            const [state, setState] = useState(initialValue);
            useEffect(() => {
                const json = window.sessionStorage.getItem(key);
                if (!json)
                    return;
                try {
                    setState(JSON.parse(json));
                }
                catch (cause) {
                    console.warn(new Error(`Found invalid JSON string in session storage:n${JSON.stringify({ key, value: json }, null, 2)}`, { cause }));
                }
            }, [setState]);
            const setter = useCallback((valueOrCallback) => {
                setState((previous) => {
                    const value = typeof valueOrCallback === "function"
                        ? valueOrCallback(previous)
                        : valueOrCallback;
                    window.sessionStorage.setItem(key, JSON.stringify(value));
                    return value;
                });
            }, [setState]);
            return [state, setter];
        }
        function App() {
            const [text, setText] = useSessionState("3ae3d85d-3521-4ccd-82cb-4c47a4665f16", "");
            return (_jsx("div", { children: _jsx("input", { onChange: (ev) => setText(ev.currentTarget.value), placeholder: "Type here then refresh", value: text }) }));
        }
        const rootElement = document.getElementById("root") ??
            document.body.appendChild(document.createElement("div"));
        createRoot(rootElement).render(_jsx(App, {}));
      </script>
    </head>
    
    <body></body>
    
    </html>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search