3

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

how do I use it outside of a component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.