Get cookie with react

ε祈祈猫儿з 提交于 2019-12-06 19:06:36

问题


I need to know if my user is connected or not. For that I want to read the cookies that I set in the server side with express-session :

app.use(session({
    secret: 'crypted key',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false } // Put true if https
  }))

app.post('/connect_user', (req, res) => {
    req.session.cookie.username = req.body.username
    findUserData('username', req.body.username, req, (userData) => {
        req.session.cookie.id = userData.id
        req.session.cookie.username = userData.username
        res.redirect('/profil')
    })
})

I tried to use react-cookie but it doesn't work however I copy/paste the npm react-cookie doc :

import React from 'react';
import Landing from './Landing';
import Home from './Home';
import Profil from './Profil';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import { instanceOf } from 'prop-types';
import { Cookies } from 'react-cookie';


class App extends React.Component {
    static propTypes = {
        cookies: instanceOf(Cookies).isRequired
      };
     
      constructor(props) {
        super(props);
     
        const { cookies } = props;
        this.state = {
          username: cookies.get('username')
        };
      }
    render() {
        console.log(this.state.name) 
        let homePage = (!this.state.username) ? <Landing/> : <Home/>
        return (
            <Router>
                <div>
                    <Route exact path='/' component={homePage}></Route>
                    <Route path='/profil' component={Profil}></Route>
                </div>
            </Router>
        )
    }
}

export default App;

Anyone know why that doesn't work ? It's weird because document.cookie render me the good result but I don't know how handle it : PHPSESSID=0nv9ic8h7pv2b63lu4v7eg3mop; user_id=21; username=Ugo; SL_G_WPT_TO=fr; SL_GWPT_Show_Hide_tmp=undefined; SL_wptGlobTipTmp=undefined

Thx for the help !


回答1:


You can use js-cookie package and can install it using npm install js-cookie --save command.

import React from 'react';
import Cookies from 'js-cookie';

class App extends React.Component {
     this.state = {
        username: Cookies.get('username')
     }

//  more code....
}  

Documentation : https://github.com/js-cookie/js-cookie

NPM : https://www.npmjs.com/package/js-cookie




回答2:


I'd recommend using universal-cookies as its simpler to use. Mind you, cookies has nothing to do with React. They are stored on the browser and you could use the browser's default API to get cookies.

Here is an example how you can use universal-cookies

import React from 'react';
// other imports...
import Cookies from 'universal-cookie';

const cookies = new Cookies();

class App extends React.Component {
     this.state = {
        username: cookies.get('username')
     }

//  more code....   

source: https://www.npmjs.com/package/universal-cookie




回答3:


If all you want is to get the cookie value by key, I would suggest using plain javascript without any dependencies.

In this example, it gets the cookie value by the key "username" with the help of Regex.

let cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*\=\s*([^;]*).*$)|^.*$/, "$1");

https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Example_2_Get_a_sample_cookie_named_test2



来源:https://stackoverflow.com/questions/51109559/get-cookie-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!