I am building a small website and in a page there are a form and a table that displays some query output based on the user input. On first loading, I have no problems because I inserted some code in the onMount function that set up the page. When the used submits the form a second time, the webpage remains the same, but onMount is not triggered. For this reason, I used the $: notation so that each time a new form is submitted, I can set up the page accordingly. The issue is that when I insert the update_buttons() function in the $: part, I get the error displayed in the thread title. Why do I get this error?
<script>
import {onMount} from 'svelte';
import Table from './Table.svelte';
import Criteria from './Criteria.svelte';
import {init_page, update_buttons} from './update-shipments.js';
export let data;
$: {
document.page=0;
document.shipments_num=data.shipments_num;
document.form_input = data.form_input;
update_buttons();
}
onMount(() => {
init_page();
update_buttons();
});
</script>
update_buttons function
export function update_buttons() {
if (document.page==0) {
document.getElementById("prev-button").disabled=true;
} else {
document.getElementById("prev-button").disabled=false;
}
if (document.page*30+30>=document.shipments_num) {
document.getElementById("next-button").disabled=true;
} else {
document.getElementById("next-button").disabled=false;
}
}
Alternatively, is there any way to run some code each time a new form is submitted, even when the page remains the same and the only thing changing are the URL parameters?
As suggested by @Stephane Vanraes i refactored the whole page to to take advantage of the svelte functionalities and now everything works. To be more specific now the buttons are set up like this
<button id="prev-button" class="btn {data.page == 0 ? "disabled" : null}" on:click={() => update_shipments("prev")}>back</button>
<button id="next-button" class="btn {data.page*30+30 >= data.shipments_num ? "disabled" : null}" on:click={() => update_shipments("next")}>forw</button>
Meanwhile the query output, like shipments_num is now solely managed as an attributed of the data variable.
on:submit
event. Do not use reactivity here. See this question. – QuiltgetElementbyId
? all of that should just be state, maybe a store even. – Snowshed