Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, store boolean value using custom hook , but it doesnt work

I using React 18 and testing with sandbox env(codepen.io).
I practice using LocalStorage and Custom Hooks, but it doesnt work as intended.. 🙁
Here is url:https://codepen.io/DogeIsFree/pen/qBYmpKj?editors=1111

and Code!

<body>
  <div id="root"></div>
  <script type="text/babel">
    const useLocalStorage = (props) =>
    {
      const [state,setState] = React.useState(()=>{
        return window.localStorage.getItem(props) ||false}
      );
      React.useEffect(()=>{
       window.localStorage.setItem(props,state)
      },[state]);
      return [state,setState];
    }
    const App = () =>{
      const [count,setCount] = React.useState(0);
      const [isLiked,setIsLiked] = useLocalStorage("isLiked");
      
      const handleLike = (event) =>{
        console.log(isLiked) // isLiked false!
        isLiked ?
          console.log("true!") // but, this is result 
        : console.log("false!"); //i expected 
        setIsLiked(!isLiked);
      }
      return(
        <>
          <span>{count}</span>
          <button onClick={handleLike}>Like</button>
        </>
      )
    }
    ReactDOM.createRoot(root).render(<App/>);
  </script>
  
</body>
</html>

In first click, state("Isliked") logged false, but in IF condition( isLiked ? console.log(true!):console.log(false!) ), logged true! .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That is because when reading from localStorage, you are getting string instead of a boolean: a string "false" is actually truthy. This is due to how the standards for localStorage are interpreted and implemented by browsers.

You should ensure that you are comparing it against a string "true" when evaluating it as a boolean. That will fix your problem:

const [state, setState] = React.useState(() => {
  return window.localStorage.getItem(props) === "true";
});

There are of course other ways to convert "true" or "false" strings to a boolean.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading