javascriptreactjscookiesjs-cookiereact-cookie

How to read cookies with react?


I have a cookie on my browser and I want to read it with react, I use it like that:

import Cookies from 'js-cookie';
console.log(Cookies.get('cookieName1'));

when I run it, I get undefined on the console, but, the cookieName1 have a value on my cookies.

How can I fix it ?


Solution

  • I have used js-cookies which works well.

    import cookies from "js-cookies";
    
    const secure = window.location.protocol === 'https'
    

    to set value in cookie use below code

    cookies.setItem("API_TOKEN", "hello", undefined, "/", undefined, secure)
    

    to get value from cookie use below code

    cookies.getItem("API_TOKEN")
    

    to remove cookie use below code

    cookies.removeItem('API_TOKEN')