0

I am making an e-store. I have the uid of logged-in user. I am trying to make a condition that if the logged in user uid is not equal to admin uid, then I do not want that user to go on the admin page. The useEffect runs infinite.

    const navigate = useNavigate();
    const user = localStorage.getItem("uid");

    useEffect(() => {

        if (user === 'at64ZIYgqaawRyCAkH6xMYBRNwS2') {
            navigate('/admin')
        }
        else {
            navigate('/home')
        }
    })
Sujith Sandeep
  • 1,185
  • 6
  • 20

3 Answers3

0

To useEffect is't running infinite:

useEffect(() => {

//Todo

}, [])

You can write variables state in [] or not.

Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36
Anh Lee
  • 11
  • 1
0

You should add dependencies array to the useEffect that means your hook should run every changes of dependencies; So if you wanna run only one time you should add an empty array to useEffect:

useEffect(() => {

        if (user === 'at64ZIYgqaawRyCAkH6xMYBRNwS2') {
            navigate('/admin')
        }
        else {
            navigate('/home')
        }
    }, []) // this [] is dependencies array
N.SH
  • 616
  • 7
  • 20
0

There are some things I want you to take into considerations.

In order to check if the user is admin or not, do not use this uid.

This might work for a single type of applications but suppose there are multiple admins trying to access the application at the same time, it will fail!

To compare the user type, you shouldn't use if else condition with the uid, instead you should fetch a get Api which takes the uid token as query and get the data from the database and then compare the user_type.

A basic example would be like this: Frontend:

const obj=axios.get("http://localhost:7099")
.then(res=>//..handle response)
.catch(err=>//..handle error)

 

Backend/Server:

USER_OBJECT:

user={
      user_type:"admin" || "default",
      user_name:...,
      user_age:...,
      .
      .
      .
      . 
}

And you can use UseEffect like this:

useEffect(() => {

//Todo

}, [])
  • You have given the right suggestion that if I have multiple admins it would be a problem. I will try the approach described by you. But for now, I have tried dependency array as well but it's still running infinitely. – Hamza Ilyas Nov 02 '22 at 09:16
  • you can also try using this method, to get rid of your infinite loop, simply use an empty dependency array like so: `const [count, setCount] = useState(0); //only update the value of 'count' when component is first mounted useEffect(() => { setCount((count) => count + 1); }, []);` This will tell React to run `useEffect` on the first render. If still this issue persist, try looking into this post [here](https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect) –  Nov 02 '22 at 10:09