Svelte 5 make $state reactive when in external module

I am trying to refactor a dragListener into a .svelte.js module passing the position of the dragged element as a reactive $state().

The Svelte 5 Docs provide an example where let position = $state() is defined inside the external module (by returning a getter function). But what shall I do, if I need to define let position = $state() inside +page.svelte?

Below I provide a minimal working example where the position of the element can be changed via a button and via drag. For both I provide handles in a helpers.svelte.js file. Inside +page.svelte I use $inspect(position) to check, whether state has updated. While inspect will fire on button click, it does not on drag.

I suppose, however, that the button-event only appears to be reactive because position is returned by handleClick(). While the lack of true reactivity is ok for a simple click action, it is an issue in the case of the drag listener.

So, how can I make position truly reactive?

Btw: I would be fine with using stores, too. However I don’t get them working in external svelte.js files either. Also, according to the above linked Svelte 5 Docs, there should be a way to solve this with the $state() rune.

+page.svelte

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><svelte:options runes="{true}" />
<script>
import { onMount } from "svelte";
import {handleIncreaseX, handleDrag} from '$lib/helpers.svelte'
let item;
let position = $state({x:0, y:0});
$inspect(position); //??? why is it only reacting to the button but not to drag?
let onclick = () => {
position = handleIncreaseX(item, position)
}
onMount(() => {
position = handleDrag(item, position);
});
</script>
<h1>Testing state: {position.x} / {position.y}</h1>
<button {onclick}>Increase X</button>
<div id="draggable" bind:this={item}>Drag Me</div>
<style>
#draggable {
background-color: black;
color: white;
width: 200px;
}
</style>
</code>
<code><svelte:options runes="{true}" /> <script> import { onMount } from "svelte"; import {handleIncreaseX, handleDrag} from '$lib/helpers.svelte' let item; let position = $state({x:0, y:0}); $inspect(position); //??? why is it only reacting to the button but not to drag? let onclick = () => { position = handleIncreaseX(item, position) } onMount(() => { position = handleDrag(item, position); }); </script> <h1>Testing state: {position.x} / {position.y}</h1> <button {onclick}>Increase X</button> <div id="draggable" bind:this={item}>Drag Me</div> <style> #draggable { background-color: black; color: white; width: 200px; } </style> </code>
<svelte:options runes="{true}" />
<script>
    import { onMount } from "svelte";
    import {handleIncreaseX, handleDrag} from '$lib/helpers.svelte'
    
    let item;
    let position = $state({x:0, y:0});

    $inspect(position); //??? why is it only reacting to the button but not to drag?
    
    let onclick = () => {
        position = handleIncreaseX(item, position)
    }
    
    onMount(() => { 
        position = handleDrag(item, position);
    });
</script>


<h1>Testing state: {position.x} / {position.y}</h1>
<button {onclick}>Increase X</button>


<div id="draggable" bind:this={item}>Drag Me</div>

<style>
    #draggable {
        background-color: black;
        color: white;
        width: 200px;
    }
</style>

helpers.svelte.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import interact from 'interactjs';
export function handleIncreaseX(item, position) {
position.x += 1;
item.style.webkitTransform = item.style.transform = `translate(${position.x}px,${position.y}px)`;
item.setAttribute('data-x', position.x);
item.setAttribute('data-y', position.y);
return position;
}
export function handleDrag(item, position) {
console.log('DRAG INIT')
interact(item).draggable({
inertia: false,
autoScroll: false,
onstart: (ev) => {
console.log('ONSTART');
},
onmove: (ev) => {
let el = ev.target;
// store the dragged position inside data-x/data-y attributes
let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;
let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;
// translate the element and update position attributes
el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`;
el.setAttribute('data-x', x);
el.setAttribute('data-y', y);
position = {x:x, y:y};
console.log('ONMOVE', position);
},
onend: (ev)=>{
console.log('ONEND');
}
});
return position;
}
</code>
<code>import interact from 'interactjs'; export function handleIncreaseX(item, position) { position.x += 1; item.style.webkitTransform = item.style.transform = `translate(${position.x}px,${position.y}px)`; item.setAttribute('data-x', position.x); item.setAttribute('data-y', position.y); return position; } export function handleDrag(item, position) { console.log('DRAG INIT') interact(item).draggable({ inertia: false, autoScroll: false, onstart: (ev) => { console.log('ONSTART'); }, onmove: (ev) => { let el = ev.target; // store the dragged position inside data-x/data-y attributes let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx; let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy; // translate the element and update position attributes el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`; el.setAttribute('data-x', x); el.setAttribute('data-y', y); position = {x:x, y:y}; console.log('ONMOVE', position); }, onend: (ev)=>{ console.log('ONEND'); } }); return position; } </code>
import interact from 'interactjs';

export function handleIncreaseX(item, position) {
    position.x += 1;
    item.style.webkitTransform =  item.style.transform = `translate(${position.x}px,${position.y}px)`;
    item.setAttribute('data-x', position.x);
    item.setAttribute('data-y', position.y);
    return position;
}


export function handleDrag(item, position) {

    console.log('DRAG INIT')

    interact(item).draggable({
        inertia: false,
        autoScroll: false,
        onstart: (ev) => {
            console.log('ONSTART');
        },
        
        onmove: (ev) => {
            let el = ev.target;

            // store the dragged position inside data-x/data-y attributes
            let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;
            let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;
        
            // translate the element and update position attributes
            el.style.webkitTransform =  el.style.transform = `translate(${x}px,${y}px)`;
            el.setAttribute('data-x', x);
            el.setAttribute('data-y', y);
            position = {x:x, y:y};

            console.log('ONMOVE', position);
        },

        onend: (ev)=>{
            console.log('ONEND');
        }
    });
    return position;
}

Comment 1: Reactivity does work perfectly fine, as long as I define the drag listener inside the +page.svelte. However, this is not an option for me.

+page.svelte

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><svelte:options runes="{true}" />
<script>
import { onMount } from "svelte";
import interact from 'interactjs';
import {handleIncreaseX} from '$lib/helpers.svelte'
let item;
let position = $state({x:0, y:0});
$inspect(position); //??? why is it only reacting to the button but not to drag?
let onclick = () => {
position = handleIncreaseX(item, position)
}
onMount(() => {
console.log('DRAG INIT')
interact(item).draggable({
inertia: false,
autoScroll: false,
onstart: (ev) => {
console.log('ONSTART');
},
onmove: (ev) => {
let el = ev.target;
// store the dragged position inside data-x/data-y attributes
let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;
let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;
// translate the element and update position attributes
el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`;
el.setAttribute('data-x', x);
el.setAttribute('data-y', y);
position = {x:x, y:y};
console.log('ONMOVE', position);
},
onend: (ev)=>{
console.log('ONEND');
}
});
});
</script>
<h1>Testing state: {position.x} / {position.y}</h1>
<button {onclick}>Increase X</button>
<div id="draggable" bind:this={item}>Drag Me</div>
<style>
#draggable {
background-color: black;
color: white;
width: 200px;
}
</style>
</code>
<code><svelte:options runes="{true}" /> <script> import { onMount } from "svelte"; import interact from 'interactjs'; import {handleIncreaseX} from '$lib/helpers.svelte' let item; let position = $state({x:0, y:0}); $inspect(position); //??? why is it only reacting to the button but not to drag? let onclick = () => { position = handleIncreaseX(item, position) } onMount(() => { console.log('DRAG INIT') interact(item).draggable({ inertia: false, autoScroll: false, onstart: (ev) => { console.log('ONSTART'); }, onmove: (ev) => { let el = ev.target; // store the dragged position inside data-x/data-y attributes let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx; let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy; // translate the element and update position attributes el.style.webkitTransform = el.style.transform = `translate(${x}px,${y}px)`; el.setAttribute('data-x', x); el.setAttribute('data-y', y); position = {x:x, y:y}; console.log('ONMOVE', position); }, onend: (ev)=>{ console.log('ONEND'); } }); }); </script> <h1>Testing state: {position.x} / {position.y}</h1> <button {onclick}>Increase X</button> <div id="draggable" bind:this={item}>Drag Me</div> <style> #draggable { background-color: black; color: white; width: 200px; } </style> </code>
<svelte:options runes="{true}" />
<script>
    import { onMount } from "svelte";
    import interact from 'interactjs';

    import {handleIncreaseX} from '$lib/helpers.svelte'
    
    let item;
    let position = $state({x:0, y:0});
    
    $inspect(position); //??? why is it only reacting to the button but not to drag?
    
    let onclick = () => {
        position = handleIncreaseX(item, position)
    }
    
    onMount(() => { 
        console.log('DRAG INIT')

        interact(item).draggable({
            inertia: false,
            autoScroll: false,
            onstart: (ev) => {
                console.log('ONSTART');
            },
            
            onmove: (ev) => {
                let el = ev.target;

                // store the dragged position inside data-x/data-y attributes
                let x = (parseFloat(el.getAttribute('data-x')) || 0) + ev.dx;
                let y = (parseFloat(el.getAttribute('data-y')) || 0) + ev.dy;
            
                // translate the element and update position attributes
                el.style.webkitTransform =  el.style.transform = `translate(${x}px,${y}px)`;
                el.setAttribute('data-x', x);
                el.setAttribute('data-y', y);
                position = {x:x, y:y};

                console.log('ONMOVE', position);
            },

            onend: (ev)=>{
                console.log('ONEND');
            }
        });
    });
</script>


<h1>Testing state: {position.x} / {position.y}</h1>
<button {onclick}>Increase X</button>


<div id="draggable" bind:this={item}>Drag Me</div>

<style>
    #draggable {
        background-color: black;
        color: white;
        width: 200px;
    }
</style>

New contributor

The_Lab is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật