0

I have login service which uses jwt. After login, user is redirected to profile page. I called the service which takes the data from the database which works very well. I can see all the logs on console but when I return the name in the html part, I can not see the name. It is written as "undefined".

const currentUser = AuthService.user();
let token = localStorage.getItem('User');

let name;

 authenticationService.findUser(jwt_decode(token)["sub"]).then (response => response.json())
  .then(response=> {
   name = response.name;
   console.log(name);
   console.log(data);
});

return (
  <div>
<h1>{name}</h1>
  </div>
   );
John Montana
  • 175
  • 10
  • 1
    Does this https://stackoverflow.com/questions/63068154/how-to-use-a-callback-in-a-render-of-react-component answer your question? – Luke Trenaman Nov 20 '21 at 20:05

2 Answers2

0

{name} in h1 in your return is not defined.

I think the problem is that you assigned name=response.name in the fetch function. You should call here setState if you are using class components or setName if you are using hooks, for example [name,setName] = useState('').

tdy
  • 36,675
  • 19
  • 86
  • 83
kaemil
  • 24
  • 3
0
 let [name, setName] = useState("");

  useEffect(() => {
    authenticationService
      .findUser(jwt_decode(token)["sub"])
      .then((response) => response.json())
      .then((response) => {
        setName(response.name);
        console.log(name);
      });
  }, []);