color-mode icon indicating copy to clipboard operation
color-mode copied to clipboard

How to set colorMode without flash based on data fetched in asyncData()?

Open katerlouis opened this issue 4 years ago • 5 comments

We use storyblok as our CMS where we've added a field to set the desired colorMode for any given "story" (blog post, page, etc.) – All these stories get funneled into one Vue component orchestrating the different story types, so forcing the colorMode with colorMode: 'black' in this component is not an option, because the colorMode needs to be fetched first.

This is how I imagine it could work, if the colorMode property would support a function as value.

export default {
  async asyncData() {
    // some fetching ...

    return {
      colorMode: fetchedColorMode,
    };
  },
  
  // would be nice being able to do this
  colorMode() {
    return this.colorMode;
  },
};

Setting the colorMode directly in asyncData() did not work. And doing it in mounted() results in a flash.

Any ideas on how to accomplish this?

katerlouis avatar Jul 06 '21 12:07 katerlouis

Hi @katerlouis

Actually this is not possible for Nuxt 2 since we use router.beforeEach to force the color mode before navigating: https://github.com/nuxt-community/color-mode-module/blob/2ca9edc4f2f55970a8f147565eb49c8d84f8157a/lib/templates/plugin.client.js#L91-L105

We cannot have the asyncData result inside, this could work in Nuxt 3 since we use <Suspense>.

atinux avatar Jul 19 '21 08:07 atinux

Do you think this could work when using Nuxt bridge? I'm not sure if Suspense is also supported in Nuxt bridge.

katerlouis avatar Nov 03 '21 08:11 katerlouis

It might be possible, but still a bit early to say.

atinux avatar Nov 24 '21 14:11 atinux

@Atinux Any chance I'm lucky and it is possible today? Because we are still very much in Need for this. :(

I would offer my help to contribute (if I get a kick start on it, I think I am capable of helping 8))

(We can't run Nuxt-bridge, though... we however do have @nuxtjs/composition-api up and running)

EDIT: Just an idea, – does it need to come from asyncData? Or could the initial color mode technically be pulled from a store state based on the routes path? I could cook up a route-to-colormode-map that gets pulled in nuxtServerInit.

katerlouis avatar Apr 21 '23 16:04 katerlouis

@Atinux I won't give up! :D AI chat bot Phind had some pretty good ideas and even had me in hope at some point. Interesting conversation: https://www.phind.com/search?cache=64d5f47a-5a8c-44d3-9bf1-cd7bada8c9fb

katerlouis avatar Apr 28 '23 11:04 katerlouis