nnam4x
nnam4x

Reputation: 149

React hook useState not updating onclick

I am trying to update the sidebar class when the closehandler function is called but the state is not updating. How do I go about that.

function RiderSidebar({ sidebar, close }) {

const [SidebarClass, setSidebarClass] = useState('sidebar')

const closeHandler = (e) => {

    e.preventDefault();
    console.log("closed click");
    setSidebarClass("user-side-bar close")
    console.log("slidebar is " + SidebarClass);

    setTimeout(() => {
        close()
    }, 1000)
}
return (
    <div className={SidebarClass} >
        <button className="close-btn" onClick={closeHandler}>X</button>

        <ul>
            <li><NavLink to='/rider/dashboard' className="user-nav"  ><DashboardIcon />  Dashboard</NavLink></li>
            <li><NavLink to='/rider/orders' className="user-nav"  ><HistoryIcon /> Orders</NavLink></li>
            <li><NavLink to='/user/logout' className="user-nav"  ><PowerSettingsNewIcon /> Logout</NavLink></li>
        </ul>
    </div >
)
}

Upvotes: 5

Views: 14948

Answers (3)

Baskaran Ajiharan
Baskaran Ajiharan

Reputation: 508

I think you add useEffect hooks to check I explain briefly what did you wrong when you click your close button closed handler function trigger and setState function calling at the same time(asynchronous) console.log statement printed. //'side bar'

in your code, you can't verify your state change or not (only you can verify from the render method) because the closed handler function triggers only one time if you want to check your className is changed or not from console.log statement you must need useEffect hook it will trigger every time after your state changed so can conform it your className is changed or not

//only trigger one time 
 useEffect(()=>{
 console.log(SidebarClass);//output 'sidebar'
 },[])
        
 //hooks trigger every time after your state changed
  useEffect(()=>{
 console.log(SidebarClass); 
 //output 'sidebar' 
 //output user-side-bar close
            })
        
 //only trigger if SidebarClass state changed
 useEffect(()=>{
 console.log(SidebarClass);
 //output 'sidebar' 
 //output user-side-bar close
 },[SidebarClass]);

Upvotes: 4

Diwakar Singh
Diwakar Singh

Reputation: 694

React batches the state update. If you will check the state update immediately after updating the state react then you may not get the updated state. You can check the updated state in render method. It should be updated there.

Upvotes: 5

zahra zamani
zahra zamani

Reputation: 1375

useState hook is asynchronous, and will not be reflected immediately.. try this:

  useEffect(() => {
    
    }, [SidebarClass]);

Upvotes: 0

Related Questions