How can I set a cookie in react?

ReactjsCookies

Reactjs Problem Overview


Orginally, I use the following ajax to set cookie.

function setCookieAjax(){
  $.ajax({
    url: `${Web_Servlet}/setCookie`,
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    headers: { 'Access-Control-Allow-Origin': '*',
               'username': getCookie("username"),
              'session': getCookie("session")
    },
    type: 'GET',
    success: function(response){
      setCookie("username", response.name, 30);
      setCookie("session", response.session, 30);}
  })
}

function setCookie(cname, cvalue, minutes) {
    var d = new Date();
    d.setTime(d.getTime() + (minutes*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

export const getUserName = (component) => {
    setCookieAjax()
 $.ajax({
	url: `${Web_Servlet}/displayHeaderUserName`,
	contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    headers: { 'Access-Control-Allow-Origin': '*',
				'username': getCookie("username"),
				'session': getCookie("session")
			},
    type: 'GET',
    success: function(response){
        component.setState({
        usernameDisplay: response.message
		})
   }.bind(component)
 })
}

Now, I want to set the cookie using the servlet's adding cookie function. But I don't know how to achieve my purpose.

Cookie loginCookie = new Cookie("user",user);  //setting cookie to expiry in 30 mins
		loginCookie.setMaxAge(30*60);
		loginCookie.setDomain("localhost:4480");
		loginCookie.setPath("/");

response.addCookie(loginCookie);

In order to extend the cookie timelimit, what should I write in the react side to receive the cookie's session time?

Reactjs Solutions


Solution 1 - Reactjs

It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the [universal-cookie repository][1] now is:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

[1]: https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie "universal-cookie repository"

Solution 2 - Reactjs

Use vanilla js, example

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Solution 3 - Reactjs

I set cookies in React using the react-cookie library, it has options you can pass in options to set expiration time.

Check it out here

An example of its use for your case:

import cookie from "react-cookie";

setCookie() => {
  let d = new Date();
  d.setTime(d.getTime() + (minutes*60*1000));

  cookie.set("onboarded", true, {path: "/", expires: d});
};

Solution 4 - Reactjs

Little update. There is a hook available for react-cookie

  1. First of all, install the dependency (just for a note)

    yarn add react-cookie

or

npm install react-cookie

2) My usage example:

// SignInComponent.js
import { useCookies } from 'react-cookie'

const SignInComponent = () => {

// ...

const [cookies, setCookie] = useCookies(['access_token', 'refresh_token'])

async function onSubmit(values) {
    const response = await getOauthResponse(values);

    let expires = new Date()
    expires.setTime(expires.getTime() + (response.data.expires_in * 1000))
    setCookie('access_token', response.data.access_token, { path: '/',  expires})
    setCookie('refresh_token', response.data.refresh_token, {path: '/', expires})

    // ...
}

// next goes my sign-in form

}

Hope it is helpful.

Suggestions to improve the example above are very appreciated!

Solution 5 - Reactjs

A very simple solution is using the sfcookies package. You just have to install it using npm for example: npm install sfcookies --save

Then you import on the file:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

create a cookie key:

const cookie_key = 'namedOFCookie';

on your submit function, you create the cookie by saving data on it just like this:

bake_cookie(cookie_key, 'test');

to delete it just do

delete_cookie(cookie_key);

and to read it:

read_cookie(cookie_key)

Simple and easy to use.

Solution 6 - Reactjs

You can use default javascript cookies set method. this working perfect.

createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
    let date = new Date();
    date.setTime(date.getTime()+(hourToExpire*60*60*1000));
    document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},

call java scripts funtion in react method as below,

createCookieInHour('cookieName', 'cookieValue', 5);

and you can use below way to view cookies.

let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);

please refer below document for more information - URL

Solution 7 - Reactjs

By default, when you fetch your URL, React native sets the cookie.

To see cookies and make sure that you can use the https://www.npmjs.com/package/react-native-cookie package. I used to be very satisfied with it.

Of course, Fetch credentials config does this when provided

credentials: "include", // or "same-origin" or "omit"

Well, but how to use it

--- after installation this package ----

to get cookies:

import Cookie from 'react-native-cookie';

Cookie.get('url').then((cookie) => {
   console.log(cookie);
});

to set cookies:

Cookie.set('url', 'name of cookies', 'value  of cookies');

only this

But if you want a few, you can do it

1- as nested:

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
    	.then(() => {
    		Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
        	.then(() => {
        		...
        	})
    	})

2- as back together

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
....

Now, if you want to make sure the cookies are set up, you can get it again to make sure.

Cookie.get('url').then((cookie) => {
  console.log(cookie);
});

Solution 8 - Reactjs

just use react-cookie library:

npm install react-cookie

index.js:

import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";
import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <CookiesProvider>
    <App />
  </CookiesProvider>,
  rootElement
);

USAGE:

React hooks:

import React from "react";
import { useCookies } from "react-cookie";

export default function App() {
  const [cookies, setCookie] = useCookies(["user"]);

  function handleCookie() {
    setCookie("user", "gowtham", {
      path: "/"
    });
  }
  return (
    <div className="App">
      <h1>React cookies</h1>
      <button onClick={handleCookie}>Set Cookie</button>
    </div>
  );
}

class-based components:

import React, { Component } from "react";
import { instanceOf } from "prop-types";
import { withCookies, Cookies } from "react-cookie";

class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  state = {
    user: this.props.cookies.get("user") || ""
  };

  handleCookie = () => {
    const { cookies } = this.props;
    cookies.set("user", "gowtham", { path: "/" }); // setting the cookie
    this.setState({ user: cookies.get("user") });
  };

  render() {
    const { user } = this.state;
    return (
      <div className="App">
        <h1>React cookies</h1>
        {user && <p>{user}</p>}
        <button onClick={this.handleCookie}>Set Cookie</button>
      </div>
    );
  }
}

export default withCookies(App);

Solution 9 - Reactjs

Use Js-cookie package

npm i js-cookie

import Cookies from 'js-cookie'

Cookies.set('auth', 'data') 
Cookies.get('auth')

This npm package worked for me & far good as well

Solution 10 - Reactjs

The Document property cookie lets you read and write cookies associated with the document. It serves as a getter and setter for the actual values of the cookies.

document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=None; Secure";

Know more

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOPfanView Question on Stackoverflow
Solution 1 - ReactjsspeckledcarpView Answer on Stackoverflow
Solution 2 - ReactjsSmakoshView Answer on Stackoverflow
Solution 3 - ReactjsbdougieView Answer on Stackoverflow
Solution 4 - ReactjsOleksii ZymovetsView Answer on Stackoverflow
Solution 5 - ReactjssergioviniciussView Answer on Stackoverflow
Solution 6 - ReactjsThilina SampathView Answer on Stackoverflow
Solution 7 - ReactjsMahdi BashirpourView Answer on Stackoverflow
Solution 8 - ReactjsRaskulView Answer on Stackoverflow
Solution 9 - ReactjsRST EntertainmentView Answer on Stackoverflow
Solution 10 - ReactjsMD SHAYONView Answer on Stackoverflow