iHeartMedia Tech Blog

Using The Moment JS Library: Cloning

Kevin | December 12, 2019
Computer with code and Christmas tree

I discovered that the startOfWorkWeek function in our ReactJS app component which returns a momentjs object was returning a different moment of time each time it was called by a source. After some debugging and reading documentation of MomentJS, it was realized that the object is mutable and any time you call, an attribute of the object it mutates. In order to fix the issue, you must clone the moment object by either calling .clone on the object itself or encapsulating the moment object in another moment object such as moment(moment). 

 

The MomentJS library is a great tool for parsing, validating, manipulating, and displaying dates and times in JavaScript. It is an awesome library that will save any developer time and resources.

 

Here is the signature for the startOfWorkWeek function:

  const momentUtc = moment().utc()

 

  const startOfWorkWeek = (dayOfWeekStart, numOfDays) => momentUtc

    .subtract(numOfDays, 'd')

    .day(dayOfWeekStart)

    .format('YYYY-MM-DD')

HWe utilized cloning within our app component using:

    // creating workflow for each of our data sources for streaming

    // using startOfWorkWeek(d), which returns a MomentJS object, to determine start date for each workflow

    // Because MomentJS objects are mutable you must clone the object since we are calling it with each

    // data source.  Cloning the objects involves simply doing the following: moment(moment)s

    const chartsDate = moment(startOfWorkWeek(0, 0))

  

    const publishedChart = createWorkflow(

      'charts',

      getPublishedChart,

      insertPublishedChart,

      publishedChartsHeader,

      chartsDate.utc().format('YYYY-MM-DD')

    )

 

MomentJS objects are mutable which means any function that you call on that object changes the state of that object which can cause varying results. Cloning creates a copy of the object, and in this example when we created our variable, chartsDate, we cloned startOfWorkWeek by calling moment() on it using moment(startOfWorkWeek).