Reputation: 13
I am trying to build a Web-Application using svelte kit. I got the following route structure:
The +layout.ts includes a load function that fetches the data from the server.
The +page.svelte consumes the fetched data using export let data: PageData;
.
I can successfully display and edit a role name with this code:
export let data: PageData;
let roleName: string = data.role.name;
...
<TextInput bind:value={roleName} />
But when i am changing the url, by clicking on a link (e.g. from "/roles/1" to "roles/2"), it does not update the role name to the new role.
I tried this code to react to an change on the fetched data:
export let data: PageData;
$: roleName = data.role.name;
...
<TextInput bind:value={roleName} />
And it solves the problem of the not updating the role name on a link click, but it introduces the problem that i cannot change the roleName by updating the value in the TextInput.
As far as i understood the $:
syntax, it is used to create a reactive statement, which means that it will be re-evaluated whenever any of its dependencies change.
But why is it triggering a re-evaluation when the roleName changes?
When adding following code to the second example:
$: console.log(data.role.name);
It logs the same role name on every keyboard input to the console.
Upvotes: 0
Views: 459
Reputation: 185210
This is an oddity/potential bug in how dependencies are tracked and not specific to SvelteKit.
The bind:value
will cause data
to be invalidated on input, causing a reset, presumably because the reactive statement creates a relationship between roleName
and data
, even though it is supposed to be one-way from data
to roleName
.
You probably can work around this by not using bind
and splitting it into input and event:
<TextInput value={roleName} on:input={e => roleName = e.target.value} />
(This requires the component to provide the respective event, usually forwarded from some regular <input>
.)
Upvotes: 0