2

I am using a datepicker to set a moment.js date which is being set in my Vuex store:

Store state:

const state = {
    arrival: '',
    departure: ''
}

Getters:

const getters = {
    arrival: state => state.arrival,
    departure: state => state.departure,

    prettyArrival: (state) => {
        if (state.arrival instanceof moment) {
            return state.arrival.format(state.prettyFormat);
        }

        return '';
    }
}

My vuex store is properly updating the arrival state(which is a moment.js object) because I can clearly see the devtools showing the updates and the original state changing.

The prettyArrival is not updating properly though. It is only being set once when the arrival changes from an empty string to a moment.js object.

My arrival getter shows in the devtools like this:

arrival:"2017-07-21T09:15:53.770Z"

When I log it I get the moment.js object though with seems to contain reactiveGetters and reactiveSetters so the reactivity seems in place.

Is there something wrong with how I set up my getter or is something else wrong here?

Any tips are welcome, if you need more info let me know.

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
  • What do you mean by `prettyArival is not updating at all (..) it is only being set once`. So it *is* being updated? Debug (or at least put log statements) inside this method and inside the if statement. In the data you say that the default value is empty string, but then you pass moment object - doesn't seem right to me, but this might be a minor issue. – Andrey Popov Jul 19 '17 at 09:29
  • @AndreyPopov When using `consolg.log` inside the getter it only seems to call the `prettyArrival` getter the first time, then it seizes the call it again. I am guessing it has something to do with caching: `a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.` But i have no Idea how this works internally. – Stephan-v Jul 19 '17 at 09:33
  • Try changing the default value to `{}` instead. Also add computed property for this getter - it might force it to recalculate ;) – Andrey Popov Jul 19 '17 at 09:36
  • 1
    How is your code different from this working example? https://jsfiddle.net/hk9oy0br/1/ – thanksd Jul 19 '17 at 13:30

1 Answers1

1

The solution lies in this answer:

Why does vue.js not update the dom with datepicker using moment.js

I did not think this was the case since I still had a couple of inputs that were updating properly. How I got that to work is still a mystery I need to solve.

The moment.js instances are not reactive so you can fix it by throwing your moment.js instance into the constructor and create a new one everytime you set it like so:

moment(this.currentDate)

this.currentDate is a moment.js instance in this case.

Stephan-v
  • 19,255
  • 31
  • 115
  • 201