When I try to use a date from Moment.js in the constructor, componentWillMount, or componentDidMount, I get the error:
Uncaught TypeError: _moment2.default.date is not a function
I am not using Webpack or any specific build tool outside of npm. Here is my relevant code:
import React from 'react';
import Moment from 'moment';
export default class Date extends React.Component {
constructor() {
super();
this.state = { day: '',
month: '',
year: '',
weekday: ''
};
}
componentDidMount() {
this.setDate();
}
setDate() {
this.state.day = Moment.date();
this.state.month = Moment.format('MMM');
this.state.year = Moment.year();
this.state.weekday = Moment.format('dddd');
}
Is this because Moment hasn't fully been loaded when the component is rendered, or is it something else? How can I get this fixed?
When I call Moment just in the render() function, I don't get this error. But, I need the date information in the state so that I can update other app components based on the date.
Way you are setting the state is not proper, and use Moment like this: Moment().
, try this:
setDate() {
this.setState({
day : Moment().date(),
month : Moment().format('MMM'),
year : Moment().year(),
weekday : Moment().format('dddd')
});
}
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