0
votes

I have this peace of code in my default.vue layout



        beforeCreate() {
          console.warn('Cookie val=' + Cookies.get('dte'));
          console.warn('Cookie val is for dark: ' + (Cookies.get('dte') === 'true'));
          var userDarkThemeEnabled = this.$store.getters.isDarkThemeEnabledUser;
          console.warn('created userDarkThemeEnabled:' + userDarkThemeEnabled);
          if (userDarkThemeEnabled == null) {
            this.goDark = false;
            return;
          }
          this.goDark = userDarkThemeEnabled;
      },


in console i see

    **Nuxt SSR**

     Cookie val=undefined

     Cookie val is for dark: false
     created userDarkThemeEnabled: false

    **Client Side**

     Cookie val=true
     Cookie val is for dark: true
     created userDarkThemeEnabled: true

Because this beforeCreate hook calls twice for SSR and client side when page reloads i got some blink for color theme in Vuetify, because variable goDark for SSR took value false and vuetify applies light theme, and then goDark became true and vuetify change theme to dark.

If i hardcode value like this.goDark=true, it will be applied for SSR and for client side during page reload. So my question is there any way to get value stored for anonymous user(who is not logged in yet but already changed theme) in SSR?

1

1 Answers

0
votes

So looks like i found solutions. In created hook i can access Server side cookie through

this.$nuxt.context.req.headers.cookie

Checked what i have in console:

SSR                                                                                                                                           
auth.strategy=local; auth.redirect=%2Fcontacts; dte=true 

So you can find piece of code which works for me

    initTheme() {
      let themeEnabled;
      if (process.server) {
        themeEnabled = this.$parseCookies(this.$nuxt.context.req)['theme'] === 'true';
      } else {
        themeEnabled = this.$store.getters.IS_DARK_THEME_ENABLED;
      }
      this.goDark = themeEnabled;  // use this for  <v-app :dark="isDarkTheme"> computed property isDarkTheme see below
      this.$setTheme(themeEnabled); // store in vuex
    }
 isDarkTheme() {return this.$vuetify.theme.dark = this.goDark;}