Why does the icon in this Astro/Svelte component flicker on refresh?

Viewed 77
<script lang="ts">
  import { onMount } from "svelte";  
  let theme = localStorage.getItem('theme') ?? 'light';
  let flag = false;
  onMount(()=>{    
    flag = true
  })
  $: if (flag) {
    if ( theme === 'dark') {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }     
    localStorage.setItem("theme", theme);
  }
  
  const handleClick = () => {    
    theme = (theme === "light" ? "dark" : "light");    
  }; 
</script>

<button on:click={handleClick}>{theme === "dark" ? "" : ""}</button>

the icon flickers when dark mode is enabled, in light mode this doesnt happen, I'm assuming this happens because its defaulting to lightmode when it initially renders, how can i fix this?

0 Answers
Related