20

I have momentjs object in state

 state = { startDate: getNow() //this funtion return a momemtJS object } 

in one function, I need to get the date one year before startDate

const dateBeforeOneYear = this.state.startDate.subtract(1, 'years'); 

But if I do like this, I modify the state by mistake

So I try to copy the state

const copyStartDate = {...this.state.startDate} const copyStartDate = this.state.startDate.subtract(1, 'years'); 

But now I get the error, substract is not a function, I guess because copyStartDate is no more MomemntJs

1
  • store date only in state variable, anytime you want moment object pass the date into moment, that will be a better approach i think. Commented Sep 14, 2018 at 12:37

3 Answers 3

32

There's a method to clone a moment object:

const yearBefore = this.state.startDate.clone().subtract(1, 'years'); 

It would also be a better idea to store a serialisable representation of the date in your component state, such as the result of calling .valueOf() on either a Date or a Moment, either of which returns the number of milliseconds since the UNIX epoch.

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

Comments

15

moment.js has its own api for cloning moment object.

var copy = momentObj.clone(); 

And I agree on storing dates serialize representation instead of Object in store.

Comments

2

It's also possible to copy a moment object through it's constructor. Like so

const firstMoment = moment("2020-08-18"); const clone = moment(firstMoment); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.