首页 > 解决方案 > React: Is it ok to check cookies for refresh token?

问题描述

I have create a log in page, which has to enter username and password to authenticate. After the authentication, I push the history to the Homepage by using react-router and set a cookie. The code is like:

const handleLogin = () =>{
        const options = {
            url: "http://test/login",
            method: "POST",
            withCredentials: true,
            headers:{
                "Accept": "application/json",
                "content-Type": "application/json;charset-UTF-8"
            },
            data: {
                "username": user,
                "password": pass,
            }
        };
        Axios(options).then(Response =>{
            if(Response.data.JWT){
                let decode = jwt_decode(Response.data.JWT);
                if(decode.id){
                    setLoginUser(decode.username);
                    setAuthenticated(true);
                    history.push('/Homepage');
                    Cookies.set("isLogged", {expires: 1} )
                }
            }else{
                alert("Invalid user");
            }  
        });
    }

I also used JWT from back-end, here the application is fine. But when I refresh the web page, I check through the cookies for the refresh token to stay in the Homepage, and remove it for log out.

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

Is it OK to get refresh token like this?

标签: javascriptreactjs

解决方案


在外部,您的功能应该是您的useEffect. 为避免这种情况,只需将其移入挂钩即可。除此之外,对我来说看起来不错。读取 cookie 是一种副作用,因此您的做法是正确的。

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

  readCookie()
},[]);

如果您想离开readCookies钩子,则必须将其包装在useCallback钩子中并在依赖项中使用它,如下所示:

const readCookiesCallback = useCallback(() => {/* your read cookies code */}, [])

useEffect(() => {
  readCookiesCallback()
}, [readCookiesCallback])

对于你正在做的事情,这是不必要的。我的第一个例子是要走的路。


推荐阅读