How to remove cookies completely using useCookies in React without leaving undefined

Viewed 4823

So I have a django-react application where I use django-rest-framework token authentication package. I would fetch the token from an API call and insert it into a hook (useCookies) that would be stored in as a cookie. The code i have for it is as follow:

import { useCookies } from "react-cookie";

const Home = () => {
     const[token, setToken, removeToken] = useCookies(['loginToken']);
}

const loginBtn = () => {
  APIService.LoginUser({
    username: username,
    password: password,
  })
    .then((response) => {
      setToken("loginToken", response.token);
    })
    .catch((error) => console.log(error));
};

now I'm trying to create a logout functionality where user can just press a logout button in order to logout. What i have so far is:

const logout = () => {
     removeToken(['loginToken']);
}

when the button is pressed, it turns my cookie's value into undefined. before

loginToken: 'asd99123jsd9asd9231'

after

loginToken: 'undefined'

From the documentation i read, it is supposed to remove the cookies completely without even leaving a cookie variable. What could i possibly miss here? Thank you so much in advance. If you need any more information, I would be more than happy to give you please be patient as this is my first React project.

3 Answers

I was having the same problem with deleting cookies. In my case, the cookie was the same when calling the removeCookie. Then I found a solution: I was not telling the path to remove the cookie function.

removeCookie('cookie-name',{path:'/'});

P.S. - Found solution here (another StackOverflow question): cookies.remove('abc') not working in reactJs

The remove() method of the cookies API deletes a cookie, given its name and URL.

browser.cookies.remove('loginToken')

You simply should give the cookie name. no need for the extra []

import { useCookies } from "react-cookie";

const [cookies, setCookie, removeCookie] = useCookies();

useEffect(() => {
   removeCookie(cookiesName);
}, [removeCookie]);

see the refences in the react-cookie npm doc:

removeCookie(name, [options]) Remove a cookie

name (string): cookie name

options (object)

Related