0

I have a react app which basically wants to give some special permission if the logged in user is an admin. For this i have a table in the db where I store all administrator emails.

I have an UseEffect which I use to verify the current logged in user if it is available in the admin user db.

  useEffect(() => {
    const getUsers = async () => {
      const data = await getDocs(adminUsersCollectionRef);

      console.log(data);

      const user = data.docs.find((x) => x.data().email === currentUser.email);
      console.log(user.data());
      if (user && user.data()) {
        console.log("inside if")
        setIsAdmin(true);
      }
      setTimeout( () => {console.log("Admin este :" + isAdmin)}, 2000);
    };

    getUsers();
  }, []);

My problem is the following: const [isAdmin, setIsAdmin] = useState(false); my isAdmin state will always be false, even if I explicitly set it inside my if condition.

Thank you in advance!

nCis
  • 68
  • 10
  • 1
    state values aren't updated until the next render cycle, so you'll need to store if they are an admin in a separate variable or trigger the change in another useEffect hook – Tom Mar 17 '22 at 10:19
  • 1
    yes, move the `setTimeout` in his own `useEffect`: `useEffect(()=>{setTimeout( () => {console.log("Admin este :" + isAdmin)}, 2000);}, [isAdmin])` – coglialoro Mar 17 '22 at 10:21
  • @coglialoro still after trying to move the setTimeout inside a useEffect of its own, i get this error: ```React Hook "useEffect" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks``` – nCis Mar 17 '22 at 11:27
  • I just not realized that setTimeout has to be outside of the already existing useEffect. It is working properly now, thank you! – nCis Mar 17 '22 at 11:34

0 Answers0