How can I set a cookie in react?

后端 未结 7 2197
忘了有多久
忘了有多久 2020-11-30 20:09

Orginally, I use the following ajax to set cookie.

function setCookieAjax(){
  $.ajax({
    url: `${Web_Servlet}/setCookie`,
    contentType: \'application/         


        
相关标签:
7条回答
  • 2020-11-30 20:37

    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.

    0 讨论(0)
  • 2020-11-30 20:39

    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 now is:

    import Cookies from 'universal-cookie';
    const cookies = new Cookies();
    cookies.set('myCat', 'Pacman', { path: '/' });
    console.log(cookies.get('myCat')); // Pacman
    
    0 讨论(0)
  • 2020-11-30 20:39

    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});
    };
    
    0 讨论(0)
  • 2020-11-30 20:45

    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 does this when it does

    credentials: "include",// or "some-origin"
    

    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);
    });
    
    0 讨论(0)
  • 2020-11-30 20:53

    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

    0 讨论(0)
  • 2020-11-30 20:56

    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!

    0 讨论(0)
提交回复
热议问题