0

Currently experiencing problem, tham I'm not able to assign state to useState const varaible.

 const [account, setAcc] = useState({});
 const [logged, setLogg] = useState(false);

 useEffect(() => {
   console.log("app");
   let jwt = localStorage.getItem("jwt");
   let username = localStorage.getItem("username");
   console.log(username + jwt);
   const API_URL = "https://localhost:7129/api/Users/ByUsername?username=";
   if (jwt != "" && username != "") {
     axios
       .get(API_URL + username, {
         headers: authHeader(),
       })
       .then((res) => {
         console.log("passed");
         console.log(res.data);
         setAcc(res.data);
         console.log(account);
         setAccount(res.data);
         console.log(account);
         setLogged();
         redirect("/index/");
       })
       .catch((res) => {
         if (res.status == 401) {
           setLogout();
           localStorage.removeItem("jwt");
           localStorage.removeItem("username");
           redirect("/login/");
         }
       });
   }
 }, []);

 function setAccount(param) {
   console.log(param);
   setAcc(param);
 } 

As you can see in console image I've attached, I set console log commands on every step. When comes to finished GET i will show in output "passed", then it will print in output response.data and then it will try to set state through method.

console

1 Answers1

-1

The problem is that the code doesn't actually set the state. It only logs the value to the console.

To fix this, you need to use the setAcc() method to set the value of the account state variable.

Kaiss B.
  • 249
  • 1
  • 12