Home > other >  Boolean value doesn't change in useState
Boolean value doesn't change in useState

Time:07-28

An Alert component is showed on invalid credentials of user input. It also has its specific close button to hide the component, it works fine only once, which shows boolean value true and when closed its false, but, when invalid credentials are inputted again then it doesn't change value and remains false as it is. Please refer to the code as

const [show, setShow] = useState(true);

useEffect(() => {
    if(error) {
      setShow(true)
    }
}, [])

        return ( 
            <>
            {
                show ?
                <div className="alert alert-warning error" role="alert">
                    <i className="bi x-lg" onClick={() => setShow(false)}></i>
                    <strong>ERROR</strong>
                </div> : null
             }
                </>
        )

As you can see I'm putting the condition when 'error' is triggered which I receive from props. If its true then the alert box should render and when closed on cancel icon should close it. It works only first time, as the value for state is false and remains as it is even though 'error' is true in useEffect.

I want to show the alert box when 'error' is true and close on click of cancel icon and show it back when 'error' is true again. What could be the best solution?

CodePudding user response:

Like krishn kumar modanval said in his comment, you should pass error as a dependency to the dependencies array in useEffect:

useEffect(() => {
    if(error) {
      setShow(true)
    }
}, [error]) // <-- error added here

I recommend checking out the useEffect documentation here, especially the "Optimizing Performance" section where it discusses how the dependencies array works.


(If this solution alone doesn't work for you, we'll need to see how the error prop that you're passing in works with the alert box code that you're showing us. Please create a stackblitz/plunkr with an MVE demonstrating your problem and we can help you debug it better.)

CodePudding user response:

it's simple follow this:

onClick={() => setShow(!show)}

this will toggle your state Value every click.

  • Related