Search code examples
javascriptsveltesveltekit

Updating data element from imported function


I am building a webpage with a form where the user can input some data and see a query output. Clicking the left and right buttons change the page of the query result. Is it possible to update the data element of the page from within an imported function? As you can see below the update_shipments function triggers the page update but currently i use a single line in the +page.svelte file to update the data.page attribute. Is it possible to do so directly from within the imported perform_query function?

<script>
import {onMount} from 'svelte';
import Table from './Table.svelte';
import Criteria from './Criteria.svelte';
import {init_page, perform_query, toggle_table} from './shipment-results.js';

export let data;

async function update_shipments(move) {
    move == "next" ? data.page++ : data.page--;
    data.shipments = await perform_query(data.form_input, data.page);
}

onMount(() => {
    init_page(data.form_input);
}); 
</script>

<div id="table-top" class="d-flex align-items-center px-3">
        <button id="prev-button" class="btn {data.page == 0 ? "disabled" : null}" on:click={() => update_shipments("prev")}>back</button>
        <span>    
            Page X of Y
        </span>
        <button id="next-button" class="btn {data.page*30+30 >= data.shipments_num ? "disabled" : null}" on:click={() => update_shipments("next")}>forw</button>
        <button class="btn ms-auto" id="expand-button" on:click={toggle_table}>+</button>
</div>

I am also open to suggestions about alternative ways to update the data.page attribute, if there are better approaches than the one I'm using now.


Solution

  • There is no way to do this within the function unless the modified object is a store. But given that this appears to be data from SvelteKit's page props, that should not be the case.

    Dependencies are only tracked within components and across props, with stores being an exception as they provide their own change notifications, so this just would not work.