Save state after refresh

185 Views Asked by At

**I have made login logout authentication in react by node and database after login when i refresh the page my cookie save state for login but my navbar menu failed to show me log out its show me login insted of that ** Below is my code of navbar---- plz anybody help me to use react hooks useEffect in my page

const RenderMenu = () => { if (state) { return ( <> Sign out

        <DropdownItem onClick={toggle}>
          <NavLink
            tag={RRNavLink}
            exact
            activeClassName="active-class"
            to="../courses"
          > {userName}
          </NavLink>
        </DropdownItem>
      </DropdownMenu>
    </>
  );
} else {
  return (
    <>
      <DropdownMenu right>
        <DropdownItem onClick={toggle}>
          <NavLink
            tag={RRNavLink}
            exact
            activeClassName="active-class"
            to="../signin"
          >
            Sign in
          </NavLink>
        </DropdownItem>
        <DropdownItem divider />

        <DropdownItem onClick={toggle}>
          <NavLink
            tag={RRNavLink}
            exact
            activeClassName="active-class"
            to="../signup"
          >
            Sign up
          </NavLink>
        </DropdownItem>
      </DropdownMenu>
    </>
  );
}

};

1

There are 1 best solutions below

0
Michael Essiet On

Your main issue isn't in your code sample so I assumed your issue was that your components were not changing when you set your authentication state to true so this is what I came up with

export default function Rendermenu() {

  const [state, setState] = useState({authstate: false})
  const [authState, setAuthstate] = useState(false)

  const authstore = localStorage.getItem("auth");

  useEffect(() => {
    localStorage.getItem('auth')
    console.log(localStorage.getItem('auth'))
  })

  function Setauth() {
    localStorage.setItem('auth', !authState)
    setAuthstate(!authState)
    window.location.reload();
    console.log(authState)
    console.log(localStorage.getItem("auth"));
  }

  function reset() {
    localStorage.clear()
    window.location.reload()
  }


  if(localStorage.getItem('auth')) return (
    <div>
      <SignOut Setauth={Setauth} />
      <button onClick={reset}>clear</button>
    </div>
  );
  return (
    <div>
      <SignIn Setauth={Setauth} />
      <button onClick={reset}>clear</button>
    </div>
  );
}

In this snippet I used localstorage instead of cookies, I found it faster and easier to use local storage. I had used js-cookies but for some reason my cookies weren't being initialised, so that's why I went with localstorage. With local storage when I tried updating a variable it wasn't updating the DOM so I decided that the best thing was to completely clear that variable from the localstorage