svelte: tick() doesn't seem to work
Describe the bug
The code below is supposed to change the clientHeight of the div when the button is pressed and then console.log the original and the new height. According to the svelte documentation, you can “use tick to ensure that the UI is updated before continuing”. But it doesn’t work and still console.logs the original height. If you replace the tick function call in line 14 with my crude customTick function, it seems to work fine.
Reproduction
<script>
import { tick } from 'svelte';
const contents = ['Hello World', 'Hello<br />World'];
let currentContent = $state(0);
let clientHeight = $state();
function customTick() {
return new Promise((resolve, reject) => setTimeout(resolve, 1));
}
function changeContent() {
console.log(`Client Height Before Change: ${clientHeight}px`);
currentContent = (currentContent + 1) % 2;
tick().then(() => console.log(`Client Height After Change: ${clientHeight}px`)); // Doesn't work
}
</script>
<button onclick={changeContent}>Change Content</button>
<br /><br />
<div bind:clientHeight style="border: 1px solid red;">{@html contents[currentContent]}</div>
Logs
No response
System Info
I used the playground on svelte.dev
Severity
annoyance
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 15 (8 by maintainers)
I agree with @harrisi. I love Svelte, but the documentation is very bare-bones at times. IMO good docs should contain as much detail as possible. Formatted correctly with descriptive headings etc. details like these don’t make docs less readable as you can just skip to the part you’re interested in.
I believe the bindings for sizes such as
clientHeightat some point were using an iframe and then it was switched toResizeObserver. I believe the Svelte’s code behavior itself has not really changed, as in checking the boundclientHeightwithin atick()after causing the element size to change would still return the same value.tick()does seem to work as documented, but not as you expect. Addconsole.log(document.querySelector('div').clientHeight);and you’ll see thattickruns after@htmlwas updated.However, the
bind:clientHeightbinding will then be triggered later by the ResizeObserver. It is not controlled by Svelte’s update loop.tickrefers to waiting for state changes to be applied to the document.I don’t know what you are trying to achieve, but coupling all this logic so tightly seems like a bad idea. Maybe you can react to
clientHeightin an $effect and not try to imperatively do something with the change after updatingcurrentContent? If you think about it they are not related 1:1, becauseclientHeightcan also change when the users changes font size or resize the browser.