Check cookie is exist in React

2.7k Views Asked by At

I have used js-cookie in my React application, here I just use a simple condition to check whether the cookie is matched or not and push history to the following route, here is my code:

const readCookie = () => {
    let cookie = false;
    if(cookie = Cookies.get("isLogged")){
        history.push('/Homepage');
        setAuthenticated(true);
    }else{
        history.push('/');
    }
}
useEffect(() => {
    readCookie()
},[]);

But the problem is, if I have many routes, so I just have to write many if conditions as much as my existing routes to check and push to that specific route, I think it doesn't make sense to do that. So, I just want to know that is there any easier way? To check the cookies and push to their paths or routes.

1

There are 1 best solutions below

0
On

Yes, you need to create Public and Private Routes please follow the steps mentioned in the link below:

https://medium.com/wesionary-team/private-and-public-routes-with-react-router-e5f814ccff2f

and you can also check this repo https://github.com/thanhbinhtran93/react-router-example