'Make AlpineJS recognize changes to objects
I'm using AlpineJS and momentjs. The user can add a bunch of datetimes and those get pushed to an array. This array is rendered to the page with an x-for.
Now I want a method setTime, that changes the time of every datetime object. In theory this is pretty easy. But I figured, that AlpineJS will not catch, that something has changed and therefore not re-render the x-for.
I'm using this.dates.map(item => item.hour(10).minute(0)); in my example here: https://jsfiddle.net/suny1vj9/
Is there a way to tell AlpineJS to rerender, since I know when this needs to be rerendered?
I also thought about having the data twice. One as moment/Date object, and one as the string representation. That solves the problem too, but I feel like there has to be a prettier solution than maintaining two similar arrays and keeping them in sync.
How would you solve this problem differently?
Solution 1:[1]
It's a known issue with MomentJS mutability. And since any change in the object replaces the original object, Alpine.js cannot detect the change. To fix it, you will have to clone() the original object after setting the hour and minutes, so that Alpine.js can detect that the object has been changed (I mean it's a new object that time)
Also, the map() function returns the new Array, so you need to change your code like this.
function test() {
return {
dates: [
moment("2022-04-23"),
moment("2022-04-25"),
moment("2022-04-26"),
moment("2022-04-27"),
moment("2022-04-28")],
setTime() {
this.dates = this.dates.map((item) => item.hour(10).minute(0).clone())
},
}
}
This will solve your problem :)
Here is the fiddle link https://jsfiddle.net/tujfyhs2/1/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hasin Hayder |
