Search code examples
javascriptreactjslocal-storagereact-router-dom

localStorage is updating but facing issue with the output, false is being interpreted as true


I am trying to display the <BR/> component if the value is true, else display the <Nothing/> component. But for some reason, despite the value being false, the <BR/> is getting displayed.

PC.js code:

import React,{useContext, useState} from 'react'
import { BRcontext } from "../App";
import './Profile.css';
import { useNavigate } from "react-router-dom"

export default function Profile() {
   const [value, setValue] = useState(false);
   localStorage.setItem("Value", value);
   console.log(value);
   const navigate = useNavigate();
   return (
       <div>
           <div className='container mt-5'>
               <div className='row'>
                   <div>
                       <h3 className='mt-5'>Send Request</h3>
                       <button className='btn btn-success mt-3 ps-3 pe-3' onClick={() => {setValue(true)}}>Request</button>
                   </div>
               </div>
           </div>
       </div>
   )
}

BR1.js code:

import React, { useContext } from "react";
import BR from "./BR";
import Nothing from './Nothing'

export default function BR1() {
    const val = localStorage.getItem('Value');
  return (
    <div>
      {console.log(val)}
      {val ? <BR/> : <Nothing/>}
    </div>
  );
}

BR.js

import React from 'react'
import './Profile.css';

export default function BR() {
    let values = false;
    return (
        <div>
            <div className='container mt-5'>
                <div className='row'>
                    <div>
                        <h3 fontSize="150px">Do you want to be a ....?</h3>
                        <button type="button" className="btn btn-success ml-5 mt-3 mr-1">YES</button>
                        <button type="button" className="btn btn-danger ms-5 mt-3 mr-1"  onClick={() => {localStorage.removeItem('Value')}}>NO</button>
                    </div>
                </div>
            </div>
        </div>
    )
}

The value in localStorage is getting updated correctly, and val is also getting updated, but still the <BR/> component is getting displayed when I want the <Nothing/> component if value is false


Solution

  • When you do localStorage.setItem("Value", value), it will register value as a string. And then when you call const val = localStorage.getItem('Value'), val would be equal to "false". And "false" is true, because it's a non-empty string.

    For this to work, you should use JSON.parse() when getting the value from localStorage and JSON.stringify() when saving it. Like below:

    Notice I commented the lines you had, so you see where I made the changes.

    // localStorage.setItem("Value", value);
    localStorage.setItem("Value", JSON.stringify(value));
    
    // const val = localStorage.getItem('Value');
    const val = JSON.parse(localStorage.getItem('Value'));