Home > Mobile >  Not able to retain state on-reload
Not able to retain state on-reload

Time:06-05

I have a search bar and when a package name is inputted, it renders the details of the package. The problem is on reload it goes back to the old state and doesn't show the package details anymore. I have two sibling components: main and navbar and an input which is the package name. I tried to use sessionStorage to save the state but that didn't work

function App() {
  const [input, setInput] = useState('');

  useEffect(() => {
    setInput(window.sessionStorage.getItem('input'));
  }, []);

  useEffect(() => {
    window.sessionStorage.setItem('input', input);
  }, [input]);

  return (
    <div className="App">
      <Navbar setInput={setInput} />
      <div className="sections">
        {input ? (
          <Main input={input} />
        ) : (
          <h1
            style={{
              color: 'black',
              position: 'absolute',
              top: '46%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
            }}
          >
            Search for a NPM package
          </h1>
        )}
      </div>
    </div>
  );
}

export default App;

CodePudding user response:

It is not so easy to see what causes to error without seeing values of state and session storage but I guess your issue related with JSON.parse. Try with these modifications inside useEffect and initial state value

function App() {
  const [input, setInput] = useState(sessionStorage.getItem('input') ? JSON.parse(sessionStorage.getItem('input') : '');

  useEffect(() => {
    if(sessionStorage.getItem('input')){
        setInput(JSON.parse(sessionStorage.getItem('input'));
    } 
  }, []);

  useEffect(() => {
    window.sessionStorage.setItem('input', input);
  }, [input]);

  return (
    <div className="App">
      <Navbar setInput={setInput} />
      <div className="sections">
        {input ? (
          <Main input={input} />
        ) : (
          <h1
            style={{
              color: 'black',
              position: 'absolute',
              top: '46%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
            }}
          >
            Search for a NPM package
          </h1>
        )}
      </div>
    </div>
  );
}
  • Related