<script>
let count = {value:0};
const increase = (data)=>{
console.log(data);
data = {...data,value: data.value+1};
}
const increment = ()=>increase(count);
</script>
<button on:click={increment}>
Clicked {count.value}
{count.value === 1 ? 'time' : 'times'}
</button>
I simplified my problem to this code. I have a clojure function that accepts an object and tries to update it. At first, I used the ‘count’ variable as a number but I thought it will not pass the reference so I changed it to an object. But either ways, the count is not change.
2
Answers
You’re just re-assigning the data variable, but to change the count state you need to assign the latest object to the count variable.
There are two problems with your code
With this line you are re-assigning a new object to data, removing the reference to the data object you passed in before. So in this case ‘count’ doesn’t change. (You can see this because in successive clicks you keep getting
value: 0
in the logs.If you change this to
You will be modifying the object you passed in because here you do keep the reference intact. With this code, successive clicks will show that count has changed.
The markup however will not update because how Svelte works, it will only update if it sees an assignment on the variable, otherwise it has no way (or at least not a performant way) to detect changes to objects. So you have to have somewhere
count = ...
for Svelte to know that count has updated.You can try this by adding
You will see that when clicking this button it will update the UI.
A solution might be to rewrite increment to
Or alternatively, rewrite
increase
to return the data object and reassign directlyedit for your comment on an answer
Notice that you can also define an inline function: