Initials disappear after refresh

Viewed 25

I have a use effect where I get the name and email from my database. Then I want to show in the header in an avatar the initials, but after I refresh the page they disappear. The commented code is the code for avatar.

 
  const [userName, setUserName] = useState({
    nameU: "",
  });
  const [avatar, setAvatar] = useState({
    initials: "",
  });
  useEffect(() => {
    let token = sessionStorage.getItem("logInToken");
    if (!token) token = localStorage.getItem("logInToken");

    if (token) {
      setAuth({ loggedIn: true });
      auth.loggedIn = true;
      const decoded: JWTDeCode = jwt_decode(token!);
      setUser({ email: decoded.email });
      axios
        .get(`http://localhost:4000/users/${decoded.email}`)
        .then((res) => {
          setUserName({ nameU: res.data.name });
          // const fullName: any = userName.nameU.split(" ");
          // const init = fullName.shift().charAt(0) + fullName.pop().charAt(0);
          // setAvatar({ initials: init });
        })

        .catch((err) => {
          console.log(err);
        });

      // const fullName: any = userName.nameU.split(" ");

      // const init = (fullName.shift()[0] + fullName.pop()[0]).toUpperCase();
      // setAvatar({ initials: init });
    } else {
      auth.loggedIn = false;
      setAuth({ loggedIn: false });
    }
  }, []);

And how I use it:

<div className="right">
                <div className="avatar">{avatar.initials}</div>
                <div className="datas">
                  <div className="name">{userName.nameU}</div>
                  <div className="email">{user.email}</div>
                </div>
1 Answers

//Try to use it like this

<div className="right">
      <div className="avatar">{avatar?.initials}</div>
                <div className="datas">
                  <div className="name">{userName?.nameU}</div>
                  <div className="email">{user?.email}</div>
                </div>
Related