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

Time:09-19

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

CodePudding user response:

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.

CodePudding user response:

Your variable isLiked contains a string. A string with some length. Hence isLiked?true:false returns true if length of your (string) variable is 1 or greater. I think this is what's happening. Change isLiked to isLiked==="isLiked".

  • Related