-1

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>
  • The code that operates after setUsername, it's commented out - but that's the code that I would expect to add initials to the page. Perhaps you could try `const fullName = res.data.name.split(" ");` if you are having trouble with userName.nameU.split. It would be useful to know what error you are getting if you uncomment that code. – James Sep 17 '22 at 12:21

1 Answers1

0

//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>