How to show and hide login and logout buttons in AppBar when other component logs in / out using localstorage

I have a App component which renders MyAppBar component which has Login and Logout button. App also renders Login form component which have a button that adds user information to local storage performing dummy successful login functionality. Login button is supposed to show Login form, however I have omitted this functionality for simplicity. Logout button clears localstorage performing dummy successful logout functionality. Both functionalities are working:

  • a button in Login component is able to add value to localstorage
  • Logout button in MyAppBar component is able to clear localstorage

Doubts:

Q1. how do I hide Login button and show Logout button, when a button in Login component adds value to localstorage?
Q2. how do I hide Loout button and show Login button, when a Logout button in MyAppBar component clears localstorage?
Q3. How can I do both without re-rendering the AppBar?

MyAppBar.js

import { AppBar, Button, Toolbar } from "@material-ui/core";
import "./styles.css";

export default function MyAppBar() {
  const logout = () => {
    localStorage.removeItem("user");
  };
  return (
    <AppBar>
      <Toolbar>
        <Button color="inherit">
          Login
        </Button>
        <Button onClick={logout} color="inherit">
          Logout
        </Button>
      </Toolbar>
    </AppBar>
  );
}

Login.js

import { Button } from "@material-ui/core";

export default function Login() {
  const login = () => {
    localStorage.setItem("user", JSON.stringify({ name: "rnj" }));
  };
  return (
    <>
      <Button variant="contained" color="inherit" onClick={login}>
        CREATE USER IN LOCALSTORAGE
      </Button>
    </>
  );
}

Check whole code in action in this codesandbox. You can run the codesandbox in new browser window by hitting this link, so that you can use DevTools to check changing localstorage.



Read more here: https://stackoverflow.com/questions/67937175/how-to-show-and-hide-login-and-logout-buttons-in-appbar-when-other-component-log

Content Attribution

This content was originally published by Rnj at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: