Search code examples
sveltesveltekit

svelte:window innerWidth undefined in the first load


I have this component to check device size

<script lang="ts">
    import { deviceSize } from "$lib/stores";

    let innerWidth;

    
    $: if (innerWidth >= 1652) {
        $deviceSize = {
            xl: true,
            lg: false,
            md: false,
            dsm: false,
            sm: false,
        };
    } else if (innerWidth >= 1240 && innerWidth < 1652) {
        $deviceSize = {
            xl: false,
            lg: true,
            md: false,
            dsm: false,
            sm: false,
        };
    } else if (innerWidth >= 794 && innerWidth < 1240) {
        $deviceSize = {
            xl: false,
            lg: false,
            md: true,
            dsm: false,
            sm: false,
        };
    } else if (innerWidth >= 640 && innerWidth < 794) {
        $deviceSize = {
            xl: false,
            lg: false,
            md: false,
            dsm: true,
            sm: false,
        };
    } else {
        $deviceSize = {
            xl: false,
            lg: false,
            md: false,
            dsm: false,
            sm: true,
        };
    }
    $: console.log(innerWidth);
</script>

<svelte:window bind:innerWidth />

and a App Component like this

<App.svelte>

<script>   
const { lg, xl } = $deviceSize;
$: isDesktop = xl || lg;
</script>

{#if isDesktop}
<DesktopComponent/>
{/if}

{#if !isDesktop}
<MobileComponent/>
{/if}

enter image description here

My problem is innerWidth always is undefined in the initial load. So isDesktop = false, then always render MobileComponent even when I use desktop. Please help me fix this.

I tried to set default value for deviceSize store, but not work as I want, it's always render as the defauft condition for whatever I use (PC, mobile).


Solution

  • I received a solution from @vnphanquang in Discord Svelte Vietnam https://discord.com/channels/1066621936546877450/1194881202331598909

    The problem is that I defined const { lg, xl } = $deviceSize;, it's const so can't update new data. The solution is changing it to $: ({ lg, xl } = $deviceSize);