Home > OS >  How to Stop useEffect running infinitely when using useNavigate inside it
How to Stop useEffect running infinitely when using useNavigate inside it

Time:11-02

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')
        }
    })

CodePudding user response:

To useEffect is't running infinite:

useEffect(() => {

//Todo

}, [])

You can write variables state in [] or not.

CodePudding user response:

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

CodePudding user response:

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

}, [])
  • Related