Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: _moment2.default.date is not a function in React app

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.

like image 421
Cassidy Avatar asked Feb 09 '17 20:02

Cassidy


1 Answers

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')
      });
  }
like image 59
Mayank Shukla Avatar answered Oct 04 '22 20:10

Mayank Shukla