React-cookie, removeCookie doesn't work when url have dynamic url or more than two depth url with url access, not by react-router-dom

hyeok·2023년 1월 13일
0
   "react": "^18.2.0"
   "react-router-dom": "5.1.2"
   "react-cookie": "^4.1.1"

When we use dynamic url or more than two depth url, the removeCookie doesn't work. In the condition that if we access to the page by the URL. Not by the react-router-dom.

힌글 요약: /report/detail 과 같이 2뎁스 이상의 url을 가진 페이지를 react-router-dom이 아닌 링크로 들어갈 경우, 그 이후엔 useCookie 에서 removeCookie가 작동 하지 않는 버그. 원인은 모름. 그냥 쿠키를 document상에서 vanilla로 삭제하는 방식으로 해결함

For example, we often try to access to the url like "URL/report/:reportId", "URL/report/reportDetail". Also we want to access to the page in url. Because we want to share the specific report. When we access to the url with authorized token, we can access to the page.

However, when we try to logout, The removeCookie doesn't work. here is the code.

Router.js

 <BrowserRouter>
            <Switch> 
                 {.......other routers.......}
                <AuthorizedRouter exact path="/report/reportDetail/:reportId" component={<ReportDetail/>} /> // This router check the token is valid
                <AuthorizedRouter exact path="/reportList" component={<ReportList/>} />
            </Switch>
</BrowserRouter>

ReportDetail.js

import {useCookie} from "react-cookie"

 const ReportDetail = ()=> { 
const [,,removeCookie] = useCookie();

const onLogout = ()=>{
    removeCookie("loginToken")
}

return <div> 
   <button onClick={onLogout}/>
</div>
}

Now, the removeCookie doesn't work at all.
However in the same logic with different url like "/reportList" which has just one depth Url. The removeCookie works well even though we accessed to the page in url.

I don't know why this bug happen. So i just used the vanilla way to remove the cookie

Solution

const onLogout = ()=>{ document.cookie = "loginToken=; expires=0; path=/;"; }

It works, but i don't like to use vanilla way in react. If there is any proper solution with this problem, let me know.

I reported this bug in react/cookie libary.
https://github.com/reactivestack/cookies/issues/346

profile
내가 만든 소프트웨어가 사람들을 즐겁게 할 수 있기 바라는 개발자

0개의 댓글