Bartek
Bartek

Reputation: 39

How to read a cookie with react-cookie?

I am building a FullStack App with React and Express. I am using react-cookie. After submit a form i set cookies in my browser then i render a new page in my application.

setCookie("jwt", `${data.jwt}`, {
  path: "/"
});
setCookie("user", `${data.name}`, {
  path: "/"
});

Then i want to read a cookie in that component and i do not know how can i do it. So if someone have any idea how to do it please write below :) Thanks :)

Upvotes: 0

Views: 9732

Answers (2)

vins
vins

Reputation: 539

You could use much simpler way like this (make sure you have installed react-cookie FIRST!)

import { useCookies } from 'react-cookie';

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

// set Cookie
setCookie('access_token','your_token_value_here')

// read cookie with 
console.log(cookies.access_token) 

Upvotes: 1

Shubham Chitransh
Shubham Chitransh

Reputation: 356

You can use the hook useCookies like this:

import { useCookies } from 'react-cookie';

const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);

const myCookie = cookies.get('cookie-name')

Upvotes: 1

Related Questions