Home > front end >  Data is displayed as undefined on reactjs
Data is displayed as undefined on reactjs

Time:11-21

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>
   );

CodePudding user response:

{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('').

CodePudding user response:

 let [name, setName] = useState("");

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