How manage Theme value persistent in QwikJS

197 views Asked by At

I'd like to handle the light/dark theme, but the code does not run on browser the first time

useTask$(({ track }) => {
    track(() => themeAppearance.value);
    if (isBrowser) {
      const savedTheme = localStorage.getItem("themeApp");
      console.log("from local storage", savedTheme);
      if (savedTheme) {
        themeAppearance.value =
          savedTheme === "dark" ? ThemeTypes.Dark : ThemeTypes.Ligth;
        return;
      }
    }
  });

only if i change the themeAppearance with the button with this function from useThemeHook

const toggleAppearance$ = $(() => {
    console.log(themeAppearance.value);

    if (themeAppearance.value === ThemeTypes.Dark) {
      themeAppearance.value = ThemeTypes.Ligth;
      backGroundPrimaryColor.value = BackdrounColor.Ligth;
      backGroundSecondaryColor.value = BackdrounColor.Ligth;

      textColorPrimary.value = TextColor.HardTextLigthBackground;
      textColorSecondary.value = TextColor.LigthTextLigthBackground;

      localStorage.setItem("themeApp", ThemeTypes.Ligth);
      return;
    }

    if (
      themeAppearance.value === ThemeTypes.Ligth &&
      panelBackground === "solid"
    ) {
      themeAppearance.value = ThemeTypes.Dark;
      backGroundPrimaryColor.value = BackdrounColor.DarkPrimarySolid;
      backGroundSecondaryColor.value = BackdrounColor.DarkSecondarySolid;

      textColorPrimary.value = TextColor.HardTextDarkBackground;
      textColorSecondary.value = TextColor.LigthTextDarkBackground;

      localStorage.setItem("themeApp", ThemeTypes.Dark);

      return;
    }

    if (
      themeAppearance.value === ThemeTypes.Ligth &&
      panelBackground === "translucent"
    ) {
      themeAppearance.value = ThemeTypes.Dark;
      backGroundPrimaryColor.value = BackdrounColor.DarkPrimaryTranslucent;
      backGroundSecondaryColor.value = BackdrounColor.DarkSecondaryTranslucent;

      textColorPrimary.value = TextColor.HardTextDarkBackground;
      textColorSecondary.value = TextColor.LigthTextDarkBackground;

      localStorage.setItem("themeApp", ThemeTypes.Dark);

      return;
    }
  });

I tried using useVisibleTask$() but it doesn't work for me because it runs after the first render so it's going to be a bad user experience its first render with default theme dark and then change to light saved theme

1

There are 1 answers

0
cmolina On

Did you try enabling eagerness?

useVisibleTask$(
  () => {
    const savedTheme = localStorage.getItem("themeApp");
    console.log("from local storage", savedTheme);
    if (savedTheme) {
      themeAppearance.value =
        savedTheme === "dark" ? ThemeTypes.Dark : ThemeTypes.Ligth;
      return;
    }
  },
  { strategy: 'document-ready' }
);