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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With