sveltesveltekitsvelte-component

Can't call fetch when a prop changes


I have a component that takes year as a prop and must fetch some data for that year and render based on the data.

export let year;

onMount(async()=>{
    data = await fetchData(year);
})

{#each data as d}
    <Child d={d}></Child>
{/each}

The prop year changes dynamically in the parent of this component (based on a dropdown). I want to fetch data every time the variable year changes.

The above code doesn't work because onMount is called only when the component is first rendered.

I tried using beforeUpdate, but that causes an infinite loop. Since the data changes inside beforeUpdate, it triggers another update.

If I try something like $: fetchData(year)

it gives me this error

"Error: Cannot call fetch eagerly during server side rendering with relative URL — put your fetch calls inside onMount or a load function instead."

Is there a way to listen to changes only on the variable year and call fetch when it changes?


Solution

  • I fixed it by using the key logic block.

    In the parent I did

    {#key year}
        <Component year={year}/>
    {/key}
    

    I know this doesn't entirely answer the question, but it fixes the problem. If someone knows how to actually call fetch when a prop is updated, please answer. Thank you.