1

so i'm creating my first fullstack website and once a user signs in it gets stored in the localStorage and i want to display the name of the user in my header once he is logged in but my header is not re rendering so nothing happens : this is the header before logging in header

and this is how i want it to Be after signing in : header after logging in this is my Layout code:

import "../assets/sass/categoriesbar.scss";
import Header from "./Header/Header";

const Layout = (props) => {

return ( 
    <>
        <Header/>
        <main>
           { props.children}
        </main>
        
    </>
 );
}

export default Layout;

and this is the toolBar in my Header :

const ToolBar = () => {
const history = useHistory();
let currentUser= JSON.parse(localStorage.getItem("user-info"));

const logoutHandler = () => {
 localStorage.clear("user-info");

 history.push("/login");
 };
 return (
   <>
   <div className={classes.NavigationBar}>
   <h1>
     <Link to="/">Pharmashop</Link>
   </h1>
   <NavLinks logout={logoutHandler}/>
   {localStorage.getItem("user-info")? 
     <h5>Welcome {currentUser.name} !</h5>
    : 
    <RegisterButton />
   }
  </div>
  </>
 


);

};

export default ToolBar;

please help me it's frustrating

PS: this is my first stackoverflow question sorry if it's unorganized and unclear and sorry for my bad english.

1
  • 1
    There's nothing quite like referring to the official docs. Commented Aug 22, 2021 at 3:05

1 Answer 1

1

Hazem, welcome to Stack Overflow.

In react, if you want the component to re-render when some data changes, that info must be in the component state. In your code the current user is a const, not bind to the component's state. This is how it could auto re-render when the user logs in:

const ToolBar = () => {
    const [currentUser, setCurrentUser] = useState(JSON.parse(localStorage.getItem("user-info")));

    const logoutHandler = () => {
     localStorage.clear("user-info");

     history.push("/login");
     };
     return (
       <>
       <div className={classes.NavigationBar}>
           <h1>
             <Link to="/">Pharmashop</Link>
           </h1>
           <NavLinks logout={logoutHandler}/>
           {currentUser? 
             <h5>Welcome {currentUser.name} !</h5>
            : 
            <RegisterButton />
           }
          </div>
      </>
    );
};

export default ToolBar;

See more about state in the official documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

that didn't quite work but i solved the problem using the context api (kind of ugly solution) but at least it works, thanks for the help anyway :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.