Search code examples
svelte

Svelte reactivity affected by initial variable value


I've started working with Svelte and I stumbled upon some unexpected behavior. This is the snippet of my app source

let currentPage = 1;
$: if (currentPage || $selectedOption) {
    fetchPage(currentPage, $selectedOption);
}

async function fetchPage(page: number, option: string) {
    //...
}

onMount(() => {
    fetchPage(currentPage, $selectedOption);
});

When I load the page for the first time fetchPage() function is called twice. However, if I'll make this change let currentPage = 0; it is properly called only once. The problem is that I need to have currentPage value initially set to 1.

I've tried also this change:

let currentChange = 0;
// ... rest the same
onMount(() => {
    fetchPage(currentPage, $selectedOption);
    currentPage = 1;
});

But this didn't help as well. Similarly any bool flags set in onMount() and then checked in if statement didn't help.

Any suggestion what else can I do?


Solution

  • You can simply use your first solution WITHOUT onMount(...).

    If you have both onMount() and $: if(currentPage || $selectedOption){, then both will try to fetch the page when the user comes to the page IF currentPage is truthy. 0 is the only number that is falsy, so for that number it's only onMount() that will fetch the page.