[Vuejs]-Dayjs with Nuxt/Vue: Button to change timezone

0👍

You need to use mapState in this situation:

Script

import { mapState } from 'vuex'
export default {
  data() {
    return {
        currentTimeZoneOutput: this.$dayjs(Date.now()).format("h:mm:ss A"),
    };
  },
  methods: {
      changeTimezone(state){
        this.$store.commit('SET_TIMEZONE', state)
        this.$dayjs.tz.setDefault(this.timezone) // EDITED
      },
      /** 
      * No need for this. By force re-rendering you run data() again 
      * too. So it will be the same each time.
      */
      /* forceRerender(){
          this.$emit("forceRerender");
      } */
  },
  computed: {
      ...mapState(['timezone'])
  }
}

Now inside your template use timezone from computed property.

...
<div><span>data timezone</span>{{ timezone }}</div>

A very good explanation about mapState is in this link.

0👍

Okay turns out – needed to add UTC to the dates first.

So instead of (for example):

this.$dayjs(Date.now()).tz("America/New_York").format("h:mm:ss A")

It becomes:

this.$dayjs.utc(Date.now()).tz("America/New_York").format("h:mm:ss A")

Now my dates are finally reactive!

Leave a comment