Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get cookies in react js using react-cookie?

The react-cookie docs have this example

import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
  static propTypes = {
    cookies: instanceOf(Cookies).isRequired
  };

  componentWillMount() {
    const { cookies } = this.props;

    this.state = {
      name: cookies.get('name') || 'Ben'
    };
  }

  handleNameChange(name) {
    const { cookies } = this.props;

    cookies.set('name', name, { path: '/' });
    this.setState({ name });
  }

Can I use cookies.get without using componentWillMount?

like image 810
Amber Normand Avatar asked Jan 22 '26 03:01

Amber Normand


1 Answers

There is a little miss use of life-cycle hooks there.

You should be giving initial value to state on class constructor.

e.g.

class Example extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      name: this.props.cookies.get('name') || 'Ben',
    }
  }
...

or if you use newer ES7 syntax just

class Example extends React.Component {
    state = {
      name: this.props.cookies.get('name') || 'Ben',
    }
...

constructor -function is not required on lower example

componentWillMount life-cycle will also be deprecated in upcoming React releases so I would recommend to avoid using it.

Replacement for it is accordingly

static getDerivedStateFromProps(nextProps, prevState){
   return {username: nextProps.username}
}

See difference here, we return normal Object which then get's passed to Components state. So in here username would be get passed to state.

like image 111
Jimi Pajala Avatar answered Jan 23 '26 18:01

Jimi Pajala